Reputation: 43
I have a windows service that i need to run at specific time of day.Suppose the time id 11:00 PM.At present i have code to run this service on everyday but how to add time variant into this i am not able to get that. Here is my code in c#..
protected override void OnStart(string[] args)
{
timer = new Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Add your code here
readDataFromAd();
}
private static void start_timer()
{
timer.Start();
}
Please help me in defining the time also along with the interval.The time Should be 11:00 PM and the timer should execute the Method Everyday.
Upvotes: 1
Views: 18866
Reputation: 5318
I would recommend changing your approach. Services are normally used for long running processes that are always running. For processes that run on a schedule, windows has a built in component called "Task Scheduler" that is designed for running applications on a schedule.
You can simply take your application service code and paste it into a windows console application and then schedule the resultant exe to run on whatever schedule you see fit by using the Windows Task Scheduler.
Hope this helps.
Upvotes: 5
Reputation: 96
Try this:
protected override void OnStart(string[] args)
{
_timer.Enabled = true;
DateTime currentTime = DateTime.Now;
int intervalToElapse = 0;
DateTime scheduleTime = Convert.ToDateTime(ConfigurationSettings.AppSettings["TimeToRun"]);
if (currentTime <= scheduleTime)
intervalToElapse = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
else
intervalToElapse = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
_timer = new System.Timers.Timer(intervalToElapse * 1000);
_timer.AutoReset = true;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//do your thing
//set it to run on a 24-hour basis
_timer.Interval = 60 * 60 * 24 * 1000;
}
Upvotes: 0
Reputation: 2433
Quartz is great, but if all you want to do is run your service once a day then the builtin Windows Task Scheduler is a good option too.
You would:
Create a task in the Task Scheduler that executes the following command at 11 PM:
NET START Your-Service-Name
Upvotes: 0
Reputation: 4413
The best option is to use Quartz schedular in windows service. Using quartz you can also schedule multiple jobs in a single service based on time for execution like daily on 5 A.M. , every hour, every minute, weekly etc. It is too flexible to use.
Upvotes: 3