2012-06-09 45 views
-1

我正在製作一個程序,它必須每30或60分鐘檢查一次數據庫,並在Windows窗體界面中顯示結果(如果有)。當然,在執行數據庫檢查時,from提供的其他函數仍應該可用。爲此,我使用System.Timers.Timer,它在UI的另一個線程上執行一個方法(如果使用這種方法出現問題,請隨時評論它)。我寫了一個小而簡單的程序來測試熱門的工作,但只注意到我無法真正將Interval設置爲1分鐘以上(我需要30分鐘到1小時)。我想出了這個解決方案:是否有其他方法來設置長計時器間隔

public partial class Form1 : Form 
{ 

    int s = 2; 

    int counter = 1; //minutes counter 

    System.Timers.Timer t; 

    public Form1() 
    { 
     InitializeComponent(); 

     t = new System.Timers.Timer(); 
     t.Elapsed += timerElapsed; 
     t.Interval = 60000; 
     t.Start(); 
     listBox1.Items.Add(DateTime.Now.ToString()); 
    } 


    //doing stuff on a worker thread 
    public void timerElapsed(object sender, EventArgs e) 
    { 
     //check of 30 minutes have passed 
     if (counter < 30) 
     { 
      //increment counter and leave method 
      counter++; 
      return; 
     } 
     else 
     { 
      //do the stuff 
      s++; 
      string result = s + " " + DateTime.Now.ToString() + Thread.CurrentThread.ManagedThreadId.ToString(); 
      //pass the result to the form`s listbox 
      Action action =() => listBox2.Items.Add(result); 
      this.Invoke(action); 
      //reset minutes counter 
      counter = 0; 
     } 


    } 

    //do other stuff to check if threadid`s are different 
    //and if the threads work simultaneously 
    private void button1_Click(object sender, EventArgs e) 
    { 
     for (int v = 0; v <= 100; v++) 
     { 

      string name = v + " " + Thread.CurrentThread.ManagedThreadId.ToString() + 
       " " + DateTime.Now.ToString(); ; 
      listBox1.Items.Add(name); 
      Thread.Sleep(1000); //so the whole operation should take around 100 seconds 
     } 

    } 
} 

不過這樣一來,正在引發Elapsed事件,並呼籲timerElapsed方法每分鐘一次,這似乎有點沒用。有沒有辦法實際設置更長的定時器間隔?

+0

我看不到問題。以毫秒錶示1小時(3600000)適合'int'。 – Tudor

+0

哈哈哈哈哈哈!確實如此,我記得在某個地方讀書時,不可能設置這樣的間隔,所以我從來沒有想過嘗試。謝謝:) –

回答

4

間隔以毫秒爲單位,這樣看來,你已經設置的時間間隔60秒:

t.Interval = 60000; // 60 * 1000 (1 minute) 

如果你想有1個小時的時間間隔,那麼你需要你的時間間隔更改爲:

t.Interval = 3600000; // 60 * 60 * 1000 (1 hour) 
+0

謝謝:)我會花上一晚試圖想出更好的東西,然後實際上試圖設置它之前,因爲我讀的地方,這是不可能的。 –

相關問題