【发布时间】:2012-03-03 06:49:14
【问题描述】:
我想制作一个简单的程序,让它在特定的时间运行。这是我的代码:
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个警报的截图:http://i.imgur.com/ipW7H.png
其中一半是错误的。 W 代表什么时候应该工作,N 代表现在。有时差异可能很大,这是为什么呢?如何解决这个问题,或者有更好的方法来发出简单的警报?
【问题讨论】: