Reputation: 1953
I need to call a function inside a window service periodically. c# vs 2008 interval should be set from config file which is the best way to do? Please suggest
while (Service1.serviceStarted)
{
CheckFile();
Thread.Sleep(60000);
}
Thread.CurrentThread.Abort();
or
private Timer timer;
private void InitializeTimer()
{
if (timer == null)
{
timer = new Timer();
timer.AutoReset = true;
timer.Interval = 60000 * Convert.ToDouble(
ConfigurationSettings.AppSettings["IntervalMinutes"]);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
}
<add key="IntervalMinutes" value="5" />
private void timer_Elapsed(object source,System.Timers.ElapsedEventArgs e)
{
RunCommands();
}
Thanks
Kj
Upvotes: 0
Views: 1208
Reputation: 2433
Go with the timer.
The code using Thread.Sleep() is more compact but it may cause your service to to be unresponsive to requests from the Service Control Manager (and appear to hang when a user tries to stop it).
Upvotes: 0
Reputation: 108
You can access and add a task to the built-in Windows Task Scheduler with this library. This also allows for more complex scheduling.
Upvotes: 0
Reputation: 2630
I would use the timer. The Thread.Sleep will cause that thread to be inactive for the specified period of time. I know you said this is for the server, but if it has anything to do with the gui that could be very bad!
BTW I believe you can read up more here...Stackoverflow Q&A
Upvotes: 0
Reputation: 10967
http://quartznet.sourceforge.net/ try Quartz.net it's a great thing on Scheduling Job's and provides lot of Job triggers which can help you .
Upvotes: 1