问题
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)
回答1:
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)
回答2:
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.
回答3:
use Quartz.net. Then you can use regex to define the interval.
来源:https://stackoverflow.com/questions/10896536/c-system-timers-timer-run-every-15min-in-sync-with-system-clock