C#, System.Timers.Timer, run every 15min in sync w

2019-03-01 10:57发布

How do I get System.Timers.Timer to trigger Elapsed events every 15 mins in sync with the system clock? In other words, I want it to trigger exactly at xx:00, xx:15, xx:30, xx:45 (where xx means any hour)

3条回答
啃猪蹄的小仙女
2楼-- · 2019-03-01 11:20

You could let it elapse every second and check whether the current time is 00, 15, 30 or 45 and only then forward the event.

A first idea would be:

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();
        }
    }
}

(Example based on this MSDN documentation)

查看更多
淡お忘
3楼-- · 2019-03-01 11:23

use Quartz.net. Then you can use regex to define the interval.

查看更多
Viruses.
4楼-- · 2019-03-01 11:30

When starting the program, or changing the event times that will be triggered, load the event times into memory (to keep from reading this data from the hard drive every second.) Then set up a timer to fire every 1 second. A timer set to fire every 1 second is very little overhead on the processor. Set one up and open task manager and you will not even notice the processor running any more than before the timer was running. Then put a check in the timer event to check if it is time to fire an event.

查看更多
登录 后发表回答