Hi
I want to write a batch job in c# that runs a task at a random(ish) interval e.g. every hour +/- 20 mins and if no update is needed, then to wait x2 the last time before running again.
What is the best method to do this?
Hi
I want to write a batch job in c# that runs a task at a random(ish) interval e.g. every hour +/- 20 mins and if no update is needed, then to wait x2 the last time before running again.
What is the best method to do this?
Consider creating a simple application, and kicking it off with the Windows Task Scheduler. The scheduler gives you a lot of control over when and what runs, and it includes time randomization.
EDIT: missed the '2x' part. In the past, I've built Windows Services to do this:
sleep(1x +/- random(20 minutes))
if nothing to do, sleep(2x +/- random(20 minutes))
can just create a timer that pops every so often and runs a method.
example:
Timer ProcessTimer = new Timer(new TimerCallback(ProcessRandomTask), null, 0,Timeout.Infinite);
private void ProcessRandomTask(object data)
{
//Do work
lock(ProcessTime)
{
//change timer
ProcessTimer.Change(GetNewTime(), Timeout.Infinite);
}
}
Everyone else's answers are pretty good, but the only thing I can contribute here is something you should not do. Do not make the application a windows service. I've seen it so many times as an answer to similar problems. That is not what windows services are for.
In my book, windows services are applications/programs that hang in the background to facilitate other programs, or do not require user input to operate. It is not to be used as a method of launching your program at time intervals.
How about logging the timestamp from the last "unnecessary" run to a database/some permanent location? Then, your first line can say:
LastRunWithoutUpdating = GetLastRunWithoutUpdating() // load from file, or db...
if (LastRunWithoutUpdating - CurrentTime < DelayInterval) {
SkipThisRun(); // sys.exit() or something
}