2012-04-04 108 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 
}