Reputation: 1716
I want to implement a method that callback a method at a precise time. We can have more than a method that can be called at the same time.
public void CallmeBack(DateTime time, Action callback)
{
}
What's the best implementation in C# ?
My quick and dirty solution was to create a dictionary Dictionary<DateTime, List<Action>>
and to make a timer every each (minute/second) and check the time (DateTime.Now
) and a current time in the test mode.
The solution have to be "Safe" if the current machine time changed. So a simple solution like this couldn't work :
Timer timer = new Timer((param) => {callback.Invoke();}, null,
(long)(time - DateTime.Now).TotalMilliseconds, Timeout.Infinite);
Edit : Typical case where simple timer don't work is DST and manual time/date adjustment. Plus, I just want the callback executed once not multiple times.
Upvotes: 1
Views: 1106
Reputation: 12978
A couple of alternatives you may want to consider:
You could use a task scheduler such as :http://taskscheduler.codeplex.com/
You could stick with a timer and listen for time changes using: SystemEvents.TimeChanged
. That event is triggered by user time changes. I assume you can handle predictable time changes (daylight saving etc.) when setting the timer in the first place. I'm not sure about NTP-related changes - you'd need to investigate that further.
Upvotes: 1
Reputation: 8390
What you are looking for is a cron library. There are many out there. Some have a lot of features and are a bit heavy. Here is a blog post about cron jobs and a library that I have used in production code.
http://blog.bobcravens.com/2009/10/an-event-based-cron-scheduled-job-in-c/
Hope that helps get you started.
Bob
Upvotes: 2