Reputation: 1
i have already design my windows service which include many tasks (same logic run each xxx seconds), but for the new task i have to do :
i'am looking for profesional code (just thread or timer squeleton) rather than a code which works.
I hope i provide you all needed info.
Best regards
Bratom
Upvotes: 0
Views: 5442
Reputation: 134105
Doing something at a specific time is not much different from doing it periodically.
Let's say you want to do something at some point in the future. We'll call that targetDate
.
DateTime targetDate = GetActionTime(); // whatever
// compute the difference between targetDate and now.
// we use UTC so that automatic time changes (like daylight savings) don't affect it
TimeSpan delayTime = targetDate.ToUniversalTime() - DateTime.UtcNow;
// Now create a timer that waits that long ...
Timer t = new Timer(TimerProc, null, delayTime, TimeSpan.FromMilliseconds(-1));
That timer will trigger the callback once. If you want that to repeat at the same time every day, you can pass the target date (or perhaps a reference to the record that describes the whole event) to the timer proc, and have the timer proc update the target date and then call Timer.Change
to change the timer's due time. Be sure to set the period to -1 milliseconds in order to prevent it from becoming a periodic timer.
Upvotes: 2
Reputation: 18620
I know you're looking for code, but when we need daily tasks to be done with our services, we construct the service and leave the execution of it up to the operating system.
Just throw a line of code in a .bat file that starts the service and schedule that batch file to run at certain times.
Upvotes: 2
Reputation: 1438
If you need a scheduling library I would reccommend Quartz.Net, which I used in different projects with good results.
Upvotes: 2
Reputation: 33272
You need something like a Cron implementation in c#, try this one: http://www.raboof.com/Projects/NCrontab/ or http://sourceforge.net/projects/cronnet/
Upvotes: 0