Adding a System.Threading.Timer to a windows service in VS 2010

10,866

Solution 1

Below is an example of how to do this. It writes a message to the Application log (as seen in the Event Viewer) every 10 seconds until the service is stopped. In your case, put your periodic logic in the OnElapsedEvent() method.

private System.Timers.Timer _timer = new System.Timers.Timer();

protected override void OnStart(string[] args)
{
    _timer.AutoReset = true;
    _timer.Interval  = 10000;  // 10 seconds
    _timer.Elapsed  += OnElapsedEvent;
    _timer.Start();
}

protected override void OnStop()
{
    _timer.Stop();
}

private void OnElapsedEvent(object sender, ElapsedEventArgs e)
{
    // Write an entry to the Application log in the Event Viewer.
    EventLog.WriteEntry("The service timer's Elapsed event was triggered.");
}

I've got a couple of detailed answers here at SO that might be of help as you start working with Windows services.

Solution 2

Would it be easier to use a scheduled task to run a little console application or similar instead of dealing with the various nuances a Windows Service can bring?

If not, you may need to review a normal article on writing windows services such as this c# article or this VB Article. Once you see how a normal service runs (a service that doesn't use a timer), you should know where to add in the timer code.

Hope that helps?

Share:
10,866
user788487
Author by

user788487

Updated on June 04, 2022

Comments

  • user788487
    user788487 over 1 year

    This is my first time working with windows service, and I am learning as I go. I am using VS 2010, Windows 7 to create a windows service that will have a timer. I have googled and browsed this site as well Use of Timer in Windows Service, Best Timer for using in a Windows service but I still am confused as to where to code for the timer in the windows service component

    I have an OnStart method and OnStop method in the service1.cs class
    Where would I code for the timer to execute the function (NOT start the windows service)?

  • user788487
    user788487 over 12 years
    Thanks very much Matt. Thats what I needed.
  • TamusJRoyce
    TamusJRoyce over 8 years
    Scheduled Tasks that run for several hours (9 hours in my case) seem to be cut off short. Not sure if a bug in code or a problem with Task Scheduler. But this alternative will be helpful. Ops here where I work is good with either or. But they might be a deciding factor.
  • Smudge202
    Smudge202 over 8 years
    @TamusJRoyce 4 year old thread; let me know if you have any questions (or better, same username on twitter). Good luck.