namespace MyApp
{
public partial class MyAppService : ServiceBase
{
private const double INTERVAL = 60 * 60 * 1000; // 60 mins (60 * 60 * 1000 millisecs); Ideally this should come from a configuration file
private System.Timers.Timer _timer = new System.Timers.Timer();
public MyAppService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// Service Started
_timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
_timer.Interval = 1000; // Executes the first run after 1 sec
_timer.Enabled = true;
}
protected override void OnStop()
{
_timer.Enabled = false;
// Service Stopped
}
protected void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_timer.Interval != INTERVAL)
_timer.Interval = INTERVAL; // Reset the timer interval to the regular value
ServiceTask();
}
private void ServiceTask()
{
try
{
// <<<<< Add your service processing code here >>>>>
}
catch (Exception ex)
{
// Log exception
}
}
}
}
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
From novice to tech pro — start learning today.
Open in new window