Windows Service - Start and Stop everyday at a particular time.

  • Thread starter Thread starter Vamshi K J
  • Start date Start date
V

Vamshi K J

Guest
Hi,

Below is my code which runs every minute once the Windows Service is started.


I want this service to START every day at a particular time (say 1:00pm) with Timer Interval every minute and STOP at a particular time ( say 10:00pm).

Need inputs please. Thanks.


namespace Service
{
partial class WindowsService : ServiceBase
{
private System.Timers.Timer RefreshTimer = null;

public Data_Service()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
try
{
int refreshTimeInterval = 60000; //Default Time interval set in milliseconds

this.RefreshTimer = new System.Timers.Timer();
this.RefreshTimer.Interval = refreshTimeInterval;

this.RefreshTimer.Elapsed += RefreshTimer_Elapsed;
this.RefreshTimer.Start();
}
catch (Exception ex)
{
throw ex;

}
finally
{

}
}

protected override void OnStop()
{
if (this.RefreshTimer != null)
{ this.RefreshTimer.Dispose(); }

}

private void RefreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (this.RefreshTimer != null)
{ this.RefreshTimer.Stop(); }

var timeToConvert = DateTime.Now;
var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est).ToString("HH:mm");
var currentDateTime = DateTime.ParseExact(targetTime, "HH:mm", null, System.Globalization.DateTimeStyles.None);

var StartDateTime = DateTime.ParseExact("14:30", "HH:mm", null, System.Globalization.DateTimeStyles.None);
var EndDateTime = StartDateTime.AddMinutes(30);

if (currentDateTime == StartDateTime || (currentDateTime >= StartDateTime && currentDateTime <= EndDateTime))
{
// logic here
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (this.RefreshTimer != null)
{ this.RefreshTimer.Start(); }
}
}
}
}




Vamshi Janagama

Continue reading...
 

Similar threads

Back
Top