【问题标题】:Timer for alarm报警定时器
【发布时间】: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 代表现在。有时差异可能很大,这是为什么呢?如何解决这个问题,或者有更好的方法来发出简单的警报?

【问题讨论】:

    标签: c# timer


    【解决方案1】:

    System.Windows.Forms.Timers 并不精确,尤其是对于大数字。不要计算Interval 的值,而是将其设置为常数,例如1000

    【讨论】:

    • 是的,我尝试将计时器间隔设置为 1000,但每秒检查一次似乎是错误的。我想要一个更好的方法,所以我想出了这个代码,它不能正常工作。
    • @irondsd:别担心,每秒一次不会对你的处理器造成伤害,即使它看起来确实有点生硬。 (除非你运行它几个星期,否则它可能看起来有点不对劲。但是你为什么不使用任务计划程序?taskschd.msc
    • 我会尝试使用它。感谢您的帮助。
    【解决方案2】:

    看看Windows Task Schedular

    基本上创建您的 EXE 并让 Windows 处理运行时间。

    How to do it via UI

    Install it Programmatically

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多