实现计时器的最佳方式是什么?一个代码样例将会很棒!对于这个问题,“最佳”被定义为最可靠(失火次数最少)和精确。如果我指定的间隔是15秒,我希望目标方法每15秒调用一次,而不是每10 - 20秒调用一次。另一方面,我不需要纳秒精度。在本例中,该方法每14.51 - 15.49秒触发一次是可以接受的。
发布于 2012-09-22 01:59:23
使用Timer
类。
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
由Timer对象上的Interval
属性指定的Elapsed
事件将每X毫秒引发一次。它将调用您指定的Event Handler
方法。在上面的示例中,它是OnTimedEvent
。
发布于 2012-09-22 02:05:51
通过使用System.Windows.Forms.Timer
类,您可以实现所需的功能。
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
}
通过使用stop()方法,您可以停止计时器。
t.Stop();
发布于 2012-09-22 02:12:30
将ServiceBase
引用到您的类,并将以下代码放入OnStart
事件中:
Constants.TimeIntervalValue = 1
(小时)..Ideally您应该在配置文件中设置此值。
StartSendingMails =要在应用程序中运行的函数名。
protected override void OnStart(string[] args)
{
// It tells in what interval the service will run each time.
Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
base.OnStart(args);
TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
}
https://stackoverflow.com/questions/12535722
复制相似问题