C# 中的计时器启动警报 - 防止它在早上 8 点之前启动的条件
Timer in C# to start an alarm - condition to prevent it from starting before 8am
我是一个完全的初学者。我正在尝试制作一个简单的程序(一种警报),它将有一个 8 小时的计时器,当时间过去时它将 运行 一个 .exe 并自行关闭,但前提是时间是 08:00 或以后。如果计时器在 00:00 和 08:00 之间流逝,我希望它等待并启动 .exe 并在 08:00.
处自行关闭
示例:
- 我在凌晨 1 点开始这个程序。 上午 9 点 计时器结束,运行 秒 Alarm.exe
并自行关闭。
- 我在凌晨 12 点开始节目。 早上 8 点 计时器
经过,运行s Alarm.exe 并自行关闭。
- 我在
晚上 11 点。早上 7 点,计时器到时了,但我希望程序 运行
Alarm.exe 并在 上午 8 点 .
自行关闭
到目前为止我的代码:
namespace Timer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
TimeSpan now = DateTime.Now.TimeOfDay;
TimeSpan eight = new TimeSpan(8, 0, 0);
TimeSpan remaining = eight - now;
if (now >= eight)
{
System.Diagnostics.Process.Start(@"Alarm.exe");
System.Windows.Forms.Application.Exit();
}
else
{
timer2 = new System.Windows.Forms.Timer(remaining); // this doesn't make any sense I know, I just can't figure out how to make another timer that uses the remaining period.....
System.Diagnostics.Process.Start(@"Alarm.exe");
System.Windows.Forms.Application.Exit();
}
}
}
}
非常感谢您的帮助,请放轻松,我是一个彻头彻尾的菜鸟,为此我花了 20 多个小时。
您需要再次 运行 您的计时器,直到当前时间与 8:00
之间的时差
您可以将您的计时器处理程序更改为:
private void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.Hour >= 8)
{
System.Diagnostics.Process.Start(@"Alarm.exe");
System.Windows.Forms.Application.Exit();
}
else
{
timer1.Interval = (int) (DateTime.Now.Date.AddHours(8) - DateTime.Now).TotalMilliseconds;
}
}
我是一个完全的初学者。我正在尝试制作一个简单的程序(一种警报),它将有一个 8 小时的计时器,当时间过去时它将 运行 一个 .exe 并自行关闭,但前提是时间是 08:00 或以后。如果计时器在 00:00 和 08:00 之间流逝,我希望它等待并启动 .exe 并在 08:00.
处自行关闭示例:
- 我在凌晨 1 点开始这个程序。 上午 9 点 计时器结束,运行 秒 Alarm.exe 并自行关闭。
- 我在凌晨 12 点开始节目。 早上 8 点 计时器 经过,运行s Alarm.exe 并自行关闭。
- 我在 晚上 11 点。早上 7 点,计时器到时了,但我希望程序 运行 Alarm.exe 并在 上午 8 点 . 自行关闭
到目前为止我的代码:
namespace Timer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
TimeSpan now = DateTime.Now.TimeOfDay;
TimeSpan eight = new TimeSpan(8, 0, 0);
TimeSpan remaining = eight - now;
if (now >= eight)
{
System.Diagnostics.Process.Start(@"Alarm.exe");
System.Windows.Forms.Application.Exit();
}
else
{
timer2 = new System.Windows.Forms.Timer(remaining); // this doesn't make any sense I know, I just can't figure out how to make another timer that uses the remaining period.....
System.Diagnostics.Process.Start(@"Alarm.exe");
System.Windows.Forms.Application.Exit();
}
}
}
}
非常感谢您的帮助,请放轻松,我是一个彻头彻尾的菜鸟,为此我花了 20 多个小时。
您需要再次 运行 您的计时器,直到当前时间与 8:00
之间的时差您可以将您的计时器处理程序更改为:
private void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.Hour >= 8)
{
System.Diagnostics.Process.Start(@"Alarm.exe");
System.Windows.Forms.Application.Exit();
}
else
{
timer1.Interval = (int) (DateTime.Now.Date.AddHours(8) - DateTime.Now).TotalMilliseconds;
}
}