开发者

C# How to call function inside a windows service at specified interval

开发者 https://www.devze.com 2023-04-04 19:30 出处:网络
I need to call a function inside a window service periodically. c# vs 2008 interval should be set from config file

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 sou开发者_如何学Crce,System.Timers.ElapsedEventArgs e)
{
    RunCommands();
}

Thanks

Kj


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 .


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


You can access and add a task to the built-in Windows Task Scheduler with this library. This also allows for more complex scheduling.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号