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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Richard LeeSoftware 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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.