How to run a script at arbitrary intervals

I want to write a batch job in C # that runs a task at a random (ish) interval, eg. every hour +/- 20 minutes, and if no update is required, then wait for x2 one last time before restarting.

What's the best way to do this?

0


a source to share


4 answers


All other answers are pretty good, but the only thing I can contribute here is what you shouldn't be doing. Do not make the application a Windows service. I've seen this so many times as an answer to similar problems. This 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. It should not be used as a way to run your program at intervals.

+1


a source


Consider building a simple application and launching it using Windows Task Scheduler. The scheduler gives you a lot of control over when and what works, and includes time randomization.

EDIT: Missing the "2x" part. In the past, I've created Windows Services to do this:



sleep(1x +/- random(20 minutes))
if nothing to do, sleep(2x +/- random(20 minutes))

      

0


a source


can just create a timer that pops up so often and starts the 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);
  }
}

      

0


a source


How do I write the timestamp from the last "unnecessary" run to a database / some permanent location? Then your first line might say:

LastRunWithoutUpdating = GetLastRunWithoutUpdating() // load from file, or db...
if (LastRunWithoutUpdating - CurrentTime < DelayInterval) {
    SkipThisRun(); // sys.exit() or something
}

      

0


a source







All Articles