闹钟定时器
我想做一个简单的程序,让它在特定的时间运行。这是我的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Alarm ft = new Alarm(dateTimePicker1.Value);
}
}
public class Alarm
{
public Timer reminder = new Timer();
public DateTime RemindAt;
public Alarm(DateTime time)
{
RemindAt = time;
reminder.Interval = (int)(RemindAt - DateTime.Now).TotalMilliseconds;
reminder.Start();
reminder.Tick += new EventHandler(reminder_Tick);
}
void reminder_Tick(object sender, EventArgs e)
{
if (RemindAt <= DateTime.Now)
{
reminder.Dispose();
MessageBox.Show("W: " + RemindAt.ToString("dd MMMM yyyy, HH:mm:ss") + "\n" + "N: " + DateTime.Now.ToString("dd MMMM yyyy, HH:mm:ss") + "\n\n");
}
}
正如你所看到的,我使用计时器,但它似乎非常不准确,我不知道为什么。以下是 6 个警报的屏幕截图:https://i.sstatic.net/IGzIh.png
其中一半是错误的。 W 代表何时应该起作用,N 代表现在。有时差异可能很大,为什么呢?如何解决这个问题,或者也许有更好的方法来发出简单的警报?
I want to make a simple program to make it run in the specific time. Here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Alarm ft = new Alarm(dateTimePicker1.Value);
}
}
public class Alarm
{
public Timer reminder = new Timer();
public DateTime RemindAt;
public Alarm(DateTime time)
{
RemindAt = time;
reminder.Interval = (int)(RemindAt - DateTime.Now).TotalMilliseconds;
reminder.Start();
reminder.Tick += new EventHandler(reminder_Tick);
}
void reminder_Tick(object sender, EventArgs e)
{
if (RemindAt <= DateTime.Now)
{
reminder.Dispose();
MessageBox.Show("W: " + RemindAt.ToString("dd MMMM yyyy, HH:mm:ss") + "\n" + "N: " + DateTime.Now.ToString("dd MMMM yyyy, HH:mm:ss") + "\n\n");
}
}
As you can seem I use timers, but it seems pretty inaccurate, I have no idea why. Here is the screenshot of 6 alarms: https://i.sstatic.net/IGzIh.png
Half of them are wrong. W stands for when it should work, N stands for now. The difference can be huge sometimes, why is that? How to fix that, or maybe there is a better way to make a simple alarm?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
System.Windows.Forms.Timer
并不精确,尤其是对于大量数据。不要计算Interval
的值,而是将其设置为某个常量,例如1000
。System.Windows.Forms.Timer
s aren't precise, especially for large numbers. Instead of calculating the value forInterval
, set it to something constant, say1000
.查看 Windows 任务时间表
基本上创建您的 EXE 并让 Windows 处理运行时间。
如何通过 UI 执行此操作
以编程方式安装
Take a Look at Windows Task Schedular
Basically create your EXE and let Windows handle the time to run.
How to do it via UI
Install it Programmatically