Run windows service using timer control
When the service need to run continuously in specific time interval, then we have to use timer control. In this example we will take a timer control and set the timer value 5 seconds. then the service will write a record in the log for every 5 seconds.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace WindowsServiceExample
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer serviceTimer = null;
string fileLocation = "C:\\servicelog.txt";
public Service1()
{
InitializeComponent();
serviceTimer = new System.Timers.Timer();
serviceTimer.Elapsed += new System.Timers.ElapsedEventHandler(serviceTimer_Elapsed);
serviceTimer.Interval = 5 * 1000;
serviceTimer.Enabled = true;
serviceTimer.Start();
}
protected override void OnStart(string[] args)
{
if (!File.Exists(fileLocation))
File.Create(fileLocation).Close();
File.AppendAllText(fileLocation, "Service started : " + DateTime.Now.ToString() + Environment.NewLine);
}
void serviceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
File.AppendAllText(fileLocation, "Service running at : " + DateTime.Now.ToString() + Environment.NewLine);
}
protected override void OnStop()
{
serviceTimer.Stop();
serviceTimer.Enabled = false;
File.AppendAllText(fileLocation, "Service stoped : " + DateTime.Now.ToString() + Environment.NewLine);
}
}
}
Output:

Useful Tools
Online Code Editor and Compiler
HTML Minifier
Online HTML Compiler/Preivew
Word Count Tool
Replace Text/Word tool
Latest Blogs
How to check if a canvas is empty or blank
Maintain div or panel scroll position after postback in asp.net update panel
Draggable button using jquery ui
Get total number of tables, views, stored procedures and functions count and names in sql server
JavaScript function to get date in mmddyyyy hhmmss ampm forma