使用System.Timer.Timer,而不是System.Threading.Timer.设置AutoReset属性为false. 在EventHandler的最后调用Start()下面代码手写的,可能有些许问题// From command line, compile with /r:System.dll using System; using System.Timers;public class Timer2 { System.Timers.Timer aTimer = new System.Timers.Timer(10000); public static void Main() { aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.AutoReset = false; aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); // Keep the timer alive until the end of Main. GC.KeepAlive(aTimer); }
执行任务的时间始终是否始终大于500毫秒,如果是,这个timer就set的不对;
如果是有时候大于500毫秒,应该可以调用新的thread来执行这个任务;
在EventHandler的最后调用Start()下面代码手写的,可能有些许问题// From command line, compile with /r:System.dll
using System;
using System.Timers;public class Timer2
{
System.Timers.Timer aTimer = new System.Timers.Timer(10000);
public static void Main()
{
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.AutoReset = false;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
aTimer.Start();
}
}