C#

How do i create a timer method in a windows service which will execute some code at a set intervals
lemargeAsked:
Who is Participating?
 
Richard LeeConnect With a Mentor Software EnthusiastCommented:
Creating the Timer (http://www.aspfree.com/c/a/C-Sharp/Timer-Objects-in-Windows-Services-with-C-sharp-dot-NET/3/)

//Initialize the timer
Timer timer = new Timer();

The idea behind the timer is that it sleeps for a specified period (defined by the interval method), and then executes the code specified with the elapsed event.

Private void OnElapsedTime(object source, ElapsedEventArgs e)
{
}

Now we can setup the timer.

In the OnStart method add code to reflect what to do when the elapsed event is raised. In this case, we need to invoke the OnElapsedTime method we defined above, set the interval (in milliseconds) the project needs to sleep, and enable the timer so it raises the Elapsed event.

The complete OnStart method looks like this:

protected override void OnStart(string[] args)
{
   //ad 1: handle Elapsed event
  timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

  //ad 2: set interval to 1 minute (= 60,000 milliseconds)
  timer.Interval = 60000;

  //ad 3: enabling the timer
  timer.Enabled = true;
}

The OnStop event also needs to be modified. A mere timer.Enabled = false suffices. The complete OnStop method looks like this:

protected override void OnStop()
{
     timer.Enabled = false;
}

DaTribe
0
 
stagepCommented:
I implemented an approach very similar to DaTribe's solution. I declared the Timer at the class level as suggested by various postings and it would still get disposed by garbage collection. In the OnStart method add GC.KeepAlive(timer); to prevent this from happening.
0
All Courses

From novice to tech pro — start learning today.