2012-02-10 89 views
1

我想製作一個簡單的程序讓它在特定的時間運行。這裏是我的代碼:鬧鐘定時器

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代表現在。有時這種差異可能很大,爲什麼呢?如何解決這個問題,或者有更好的方法來做出簡單的警報?

回答

1

System.Windows.Forms.Timer s不準確,特別是對於大數字。不要計算Interval的值,而應將其設置爲某個常量,如1000

+0

呀,我試圖計時器的時間間隔設置爲1000,但它似乎是錯誤的,檢查它的每一秒。我想要一個更好的方法,所以我想出了這個代碼,它不能正常工作。 – irondsd 2012-02-11 09:37:23

+0

@irondsd:不要擔心,即使看起來有點駭人聽聞,每秒一次也不會傷害你的處理器。 (除非你運行幾個星期,否則它可能看起來有點不對,但爲什麼你不使用Task Scheduler?'taskschd.msc') – Ryan 2012-02-11 16:38:35

+0

我會嘗試使用它。感謝幫助。 – irondsd 2012-02-12 17:28:37