如何让 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()
{
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 文档 http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)