1

如何让 System.Timers.Timer 每 15 分钟触发一次 Elapsed 事件,与系统时钟同步?换句话说,我希望它恰好在 xx:00、xx:15、xx:30、xx:45 触发(其中 xx 表示任何时间)

4

3 回答 3

0

您可以让它每秒过去一次,并检查当前时间是 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 文档的示例)

于 2012-06-05T11:38:33.630 回答
0

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

于 2014-04-13T16:11:45.900 回答
0

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

于 2012-06-05T11:43:42.867 回答