I need help. I have Windows Service and I need run this service every hour in specific minute for example: 09:05, 10:05, 11:05,.... My service now start every hour but every hour from time when i start this service. So how can I achieve my needs.
My code:
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Starting Service {0}");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
this.WriteToFile("Stopping Service {0}");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
this.WriteToFile(" interval start {0}");
} }
You should check current time every 'n' seconds (1 as example) from timer:
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Starting Service {0}");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 1000; // 1000 ms => 1 second
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
this.WriteToFile("Stopping Service {0}");
}
private int lastHour = -1;
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
var curTime = DateTime.Now; // Get current time
if (lastHour != curTime.Hour && curTime.Minute == 5) // If now 5 min of any hour
{
lastHour = curTime.Hour;
// Some action
this.WriteToFile(" interval start {0}");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With