Nov 18, 2008

Schedule a task using C# code

I needed to schedule a task to run every day at 9:00 p.m. in the night. I had an addition al requirement that the task be scheduled only if the FileSystemwatcher alerts us of new files being available for processing.

Thus the files could be recieved anytime during the day, but despite that the task should be schduled to run exactly at 9:00 p.m. in the night.

So I used the following code to schedule a task(using System.Threading.Timer and TimeSpan classes)

DateTime d = DateTime.Now;

timer = new Timer(new TimerCallback(Update), null,
TimeSpan.FromMinutes(21 * 60 - (d.Hour * 60 + d.Minute)),
TimeSpan.FromMilliseconds(-1));


Note I used TimeSpan.FromMillisecnods(-1) to disable periodic signalling

kick it on DotNetKicks.com