Groups | Blog | Home
all groups > c# > june 2006 >

c# : Using time for scheduling task.


archana
6/12/2006 9:34:20 PM
Hi all,

I want to develop one windows service in which i want to provide some
scheduling facility.

What i want is to take start time frm one xml file and then at that
specified start time.

Which timer should i use in windows service to start particular process
at user specified time.

Means how to do this. Should i add ontimerevent and write loop to
continuously check system time and user specified time.

Can someone tell me what is correct way of doing it,

Any help will be truely appreciated.

Thanks in advance.
kh
6/13/2006 8:47:03 AM
archana

i have a scheduling Windows Service working using System.Timers.Timer and it
is perfectly adequate for this task. how you use the timer depends on your
needs, but you can do something like this easily enough..

System.Timers.Timer timer;
public MyService()
{
InitializeComponent();
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}

protected override void OnStart(string[] args)
{
// set interval from config
try
{
this.timer.Interval =
Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["TimerIntervalMinutes"]) * 60 * 1000;
}
catch
{
this.timer.Interval = 3600000;
}
timer.Start();
}

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Stop();
try
{
// do something
}
finally
{
timer.Start();
}
}
John Timney (MVP)
6/13/2006 2:14:33 PM
Any reason why you cant use the scheduler service built into windows?

Regards

John Timney (MVP)


[quoted text, click to view]

archana
6/13/2006 9:42:47 PM
Hi ,

Thanks for your reply.

But i want to implement functionality like allowing user to specify
start time and at that time only daily my task should run.

But timer is allowing me to set interval only.

What i did is i calcluated difference between current time and user
specified time and set that as a interval.

But my problem is for first time it is working properly but how will i
set timer interval to run it on next day at the same time.

If i am wrong please correct me.

Thanks.

[quoted text, click to view]
kh
6/13/2006 11:51:03 PM
this is exactly what i do. i only use the timer as a "heartbeat" for the main
scheduling functionality. in the Timer.Elapsed event handler i check if any
of my jobs are due. my jobs are actually configured in the App.config file,
but you could easily write something to do the following (most of the
supporting code has been omitted for clairity):

class MyService : ServiceBase
{
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Stop();
try
{
foreach(Job j in myJobsCollection)
if(j.JobIsDue(DateTime.Now))
j.Run();
}
finally
{
timer.Start();
}
}
}

class Job
{
public bool JobIsDue(DateTime dt)
{
return dt.TimeOfDay >= mySpecifiedRunTime;
}
}
AddThis Social Bookmark Button