Windows service scheduling to run daily once a day at 6:00 AM
Here, you have 2 ways to execute your application to run at 6 AM daily.
1) Create a console application and through windows scheduler execute on 6 AM.
2) Create a timer (System.Timers.Timer) in your windows service which executes on every defined interval and in your function, you have to check if the system time = 6 AM then execute your code
ServiceTimer = new System.Timers.Timer();
ServiceTimer.Enabled = true;
ServiceTimer.Interval = 60000 * Interval;
ServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(your function);
Note: In your function you have to write the code to execute your method on 6 AM only not every time
Here is code that will run within a service every day at 6AM.
include:
using System.Threading;
also ensure you declare your timer within the class:
private System.Threading.Timer _timer = null;
The StartTimer function below takes in a start time and an interval period and is currently set to start at 6AM and run every 24 hours. You could easily change it to start at a different time and interval if needed.
protected override void OnStart(string[] args)
{
// Pass in the time you want to start and the interval
StartTimer(new TimeSpan(6, 0, 0), new TimeSpan(24, 0, 0));
}
protected void StartTimer(TimeSpan scheduledRunTime, TimeSpan timeBetweenEachRun) {
// Initialize timer
double current = DateTime.Now.TimeOfDay.TotalMilliseconds;
double scheduledTime = scheduledRunTime.TotalMilliseconds;
double intervalPeriod = timeBetweenEachRun.TotalMilliseconds;
// calculates the first execution of the method, either its today at the scheduled time or tomorrow (if scheduled time has already occurred today)
double firstExecution = current > scheduledTime ? intervalPeriod - (current - scheduledTime) : scheduledTime - current;
// create callback - this is the method that is called on every interval
TimerCallback callback = new TimerCallback(RunXMLService);
// create timer
_timer = new Timer(callback, null, Convert.ToInt32(firstExecution), Convert.ToInt32(intervalPeriod));
}
public void RunXMLService(object state) {
// Code that runs every interval period
}
You don't need a service for this. Just create a regular console app, then use the Windows scheduler to run your program at 6am. A service is when you need your program to run all the time.