实现“计时器”的最佳方式是什么?(复制)

时间:2022-09-13 20:03:31

Possible Duplicate:
How do you add a timer to a C# console application

可能重复:如何向c#控制台应用程序添加计时器

What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 seconds, not every 10 - 20 seconds. On the other hand, I don't need nanosecond accuracy. In this example, it would be acceptable for the method to fire every 14.51 - 15.49 seconds.

实现计时器的最佳方式是什么?代码示例将非常棒!对于这个问题,“best”被定义为最可靠的(最少数量的错误)和精确。如果我指定15秒的间隔,我希望目标方法每15秒调用一次,而不是每10 - 20秒调用一次。另一方面,我不需要十亿分之一秒的精度。在本例中,方法每14.51 - 15.49秒触发一次是可以接受的。

4 个解决方案

#1


215  

Use the Timer class.

使用定时器类。

https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.timers.timer(v = vs.110). aspx

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!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify, in the example above it is OnTimedEvent

每隔X毫秒就会引发事件,由Timer对象上的Interval属性指定。它将调用您指定的事件处理程序方法,在上面的示例中,它是OnTimedEvent

#2


28  

By using System.Windows.Forms.Timer class you can achieve what you need.

通过使用System.Windows.Forms。计时器类可以实现所需。

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
}

By using stop() method you can stop timer.

通过使用stop()方法,您可以停止计时器。

t.Stop();

#3


20  

It's not clear what type of application you're going to develop (desktop, web, console...)

目前还不清楚要开发什么样的应用程序(桌面、web、控制台……)

The general answer, if you're developing Windows.Forms application, is use of

一般的答案是,如果你正在开发Windows。申请表格,是用的

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

System.Windows.Forms。定时器类。这样做的好处是它在UI线程上运行,所以简单地定义它,订阅它的Tick事件,并在每15秒运行你的代码。

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

如果您做了其他事情,那么windows窗体(问题中不清楚),您可以选择system . timer。Timer,但是这个运行在另一个线程上,所以如果您要对它经过的事件中的一些UI元素进行操作,您必须使用“调用”访问来管理它。

#4


2  

Reference ServiceBase to your class and put the below code in the OnStartevent:

引用ServiceBase到您的类,并将下面的代码放在OnStartevent中:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

常量。TimeIntervalValue = 1(小时). .理想情况下,应该在配置文件中设置此值。

StartSendingMails = function name you want to run in the application.

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));
        }

#1


215  

Use the Timer class.

使用定时器类。

https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.timers.timer(v = vs.110). aspx

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!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify, in the example above it is OnTimedEvent

每隔X毫秒就会引发事件,由Timer对象上的Interval属性指定。它将调用您指定的事件处理程序方法,在上面的示例中,它是OnTimedEvent

#2


28  

By using System.Windows.Forms.Timer class you can achieve what you need.

通过使用System.Windows.Forms。计时器类可以实现所需。

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
}

By using stop() method you can stop timer.

通过使用stop()方法,您可以停止计时器。

t.Stop();

#3


20  

It's not clear what type of application you're going to develop (desktop, web, console...)

目前还不清楚要开发什么样的应用程序(桌面、web、控制台……)

The general answer, if you're developing Windows.Forms application, is use of

一般的答案是,如果你正在开发Windows。申请表格,是用的

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

System.Windows.Forms。定时器类。这样做的好处是它在UI线程上运行,所以简单地定义它,订阅它的Tick事件,并在每15秒运行你的代码。

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

如果您做了其他事情,那么windows窗体(问题中不清楚),您可以选择system . timer。Timer,但是这个运行在另一个线程上,所以如果您要对它经过的事件中的一些UI元素进行操作,您必须使用“调用”访问来管理它。

#4


2  

Reference ServiceBase to your class and put the below code in the OnStartevent:

引用ServiceBase到您的类,并将下面的代码放在OnStartevent中:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

常量。TimeIntervalValue = 1(小时). .理想情况下,应该在配置文件中设置此值。

StartSendingMails = function name you want to run in the application.

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));
        }