2012-04-04 109 views
3

我有一個計時器打勾,我想每隔30分鐘啓動一次背景工作。計時器滴答滴答的等值30分鐘是多少?等於30分鐘的計時器滴答聲是多少?

下面下面的代碼:

 _timer.Tick += new EventHandler(_timer_Tick); 
     _timer.Interval = (1000) * (1);    
     _timer.Enabled = true;      
     _timer.Start();  

    void _timer_Tick(object sender, EventArgs e) 
    { 
     _ticks++; 
     if (_ticks == 15) 
     { 
      if (!backgroundWorker1.IsBusy) 
      { 
       backgroundWorker1.RunWorkerAsync(); 
      } 

      _ticks = 0; 
     } 
    } 

我不知道這是否是最好的方式或者如果任何人有一個更好的建議。

+0

這是C#?請正確標記並標題。 – BoltClock 2012-04-04 12:39:10

+0

你好BoltClock抱歉,它的完成:) – 2012-04-04 12:42:26

回答

12

定時器的Interval屬性以毫秒爲單位指定,而不是滴答聲。

因此,對於激發每30分鐘的計時器,簡單地做:

// 1000 is the number of milliseconds in a second. 
// 60 is the number of seconds in a minute 
// 30 is the number of minutes. 
_timer.Interval = 1000 * 60 * 30; 

不過,我並不清楚你所使用Tick事件。我想你的意思是Elapsed

編輯由於CodeNaked表明,您所說的是System.Windows.Forms.Timer,而不是System.Timers.Timer。幸運的是,我的回答適用於兩者:)

最後,我不明白你爲什麼在你的timer_Tick方法中保持一個計數(_ticks)。你應該重新寫它如下:

void _timer_Tick(object sender, EventArgs e) 
{ 
    if (!backgroundWorker1.IsBusy) 
    { 
     backgroundWorker1.RunWorkerAsync(); 
    } 
} 
+0

您好RB好滴答 - 只要計數 - 當它達到角蛋白值它踢開backgroundWorker1.RunWorkerAsync();你是否建議這應該以另一種方式完成? – 2012-04-04 12:43:57

+1

OP可能使用[WinForms Timer](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick.aspx)。 – CodeNaked 2012-04-04 12:44:50

+0

嗨代碼裸體是的OP是使用WinForm計時器:D – 2012-04-04 12:45:42

0

沒有得到好的問題。但是,如果你只是想要30分鐘的時間間隔,然後給 timer1.interval = 1800000;

//有10000個蜱在毫秒(不要忘記這一點)

+0

米爾意味着千信不信由你。 一秒鐘內有1000毫秒。一米1000毫米。 – 2016-12-07 10:29:36

1

爲了使代碼更易讀,你可以使用TimeSpan類:

_timer.Interval = TimeSpan.FromMinutes(30).TotalMilliseconds; 
0
using Timer = System.Timers.Timer; 

[STAThread] 

static void Main(string[] args) { 
    Timer t = new Timer(1800000); // 1 sec = 1000, 30 mins = 1800000 
    t.AutoReset = true; 
    t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); 
    t.Start(); 
} 

private static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { 
// do stuff every 30 minute 
}