C#,System.Timers.Timer,每15分钟与系统时钟同步运行

如何让System.Timers.Timer每15分钟触发一次与系统时钟同步的Elapsed事件? 换句话说,我希望它完全触发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() { 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(); } } } 

(基于此MSDN文档的示例)

启动程序或更改将触发的事件时间时,将事件时间加载到内存中(以防止每秒从硬盘驱动器读取此数据。)然后设置计时器每1秒触发一次。 设置为每1秒触发一次的计时器在处理器上的开销非常小。 设置一个并打开任务管理器,你甚至不会注意到处理器运行的时间超过计时器运行之前。 然后检查计时器事件以检查是否是触发事件的时间。

使用Quartz.net。 然后,您可以使用正则表达式来定义间隔。