How to schedule a windows service in .NET
Osama | March 29, 2010I had a requirement of automate a task which could run after every 5 minutes. After spending some time on research, I decided to make a windows service and automate it. Automating a windows service is a bit tricky and it gave me a little hard time. Hence, I am sharing what did I code to complete the task.
When a new service created, OnStart & OnStop methods are initialized by default. You need to play with timers to get the task done.
Below is the code snippet which shows how to automate the windows service.
public partial class Service1
{
public Timer tm; //initialize a new timer instance
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
tm = new Timer();
tm.AutoReset = true; //timer will reset and call the event handler function itself
tm.Interval = 60000; // time interval in milliseconds
tm.Elapsed += new ElapsedEventHandler(timer_start); //event which needs to be fired
//once the timer reaches its maximum value
tm.Start(); //start the timer
}
protected void timer_start(object sender, ElapsedEventArgs e)
{
//Perform your task here
}
protected override void OnStop()
{
tm.Start(); //start the timer again and it will call the event hander function again
}
The above mentioned code snippet is self explanatory. I hope it helps whoever reads the post.
Feel free to ask questions









