C# C、 System.Timers.Timer,与系统时钟同步,每15分钟运行一次
如何使System.Timers.Timer与系统时钟同步,每15分钟触发一次经过的事件?换句话说,我希望它在xx:00、xx:15、xx:30、xx:45准确触发,其中xx表示任何时间您可以让它每秒经过一次,检查当前时间是00、15、30还是45,然后才转发事件 第一个想法是:C# C、 System.Timers.Timer,与系统时钟同步,每15分钟运行一次,c#,timer,system,sync,clock,C#,Timer,System,Sync,Clock,如何使System.Timers.Timer与系统时钟同步,每15分钟触发一次经过的事件?换句话说,我希望它在xx:00、xx:15、xx:30、xx:45准确触发,其中xx表示任何时间您可以让它每秒经过一次,检查当前时间是00、15、30还是45,然后才转发事件 第一个想法是: private static System.Timers.Timer aTimer; private static System.DateTime _last; public static void Main() {
private static System.Timers.Timer aTimer;
private static System.DateTime _last;
public static void Main()
{
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
DateTime time =
new DateTime( 1,1,1, DateTime.Now.Hours, DateTime.Now.Minute );
if( time.Minute==0 ||time.Minute==15 || time.Minute==30 || time.Minute==45 )
{
// Avoid multiple notifications for the same quarter.
if ( _last==DateTime.MinValue || _last!=time )
{
_last = time;
// Do further processing.
doProcessing();
}
}
}
基于的示例启动程序或更改将触发的事件时间时,将事件时间加载到内存中,以防止每秒从硬盘读取此数据。然后设置一个计时器,每1秒启动一次。设置为每1秒触发一次的计时器在处理器上的开销非常小。设置一个并打开任务管理器,您甚至不会注意到处理器运行的时间超过计时器运行之前的时间。然后在计时器事件中进行检查,以检查是否是触发事件的时间。使用Quartz.net。然后您可以使用正则表达式来定义间隔。您可以让它每秒钟消失一次,并检查当前时间是否为00、15、,30或45,然后才转发事件。由于其他系统活动,“精确”不太可能发生…@MitchWheat-“不可能”不太可能发生,因为我们有很多工具,而且不是微秒。首先将计时器的超时值设置为毫秒,相当于15分钟。然后检查系统时钟是否给出毫米分钟值,如00、15、30或45。如果为TRUE,则启动计时器。计时器将自动启动计时器。从每个时间间隔开始,已用功能。当然,这只是一个想法。请确保将AutoReset属性设置为false。从DateTime开始,每次重新计算下一个时间间隔。现在,它保持准确。