I want to execute a function every 60 seconds in C#. I could use the Timer class like so:
timer1 = new Timer();
timer1.Tick = new EventHandler(timer1_Tick);
timer1.Interval = 60 * 1000; // in miliseconds
timer1.Start();
Question is I have a long running process. Occasionally it make take several minutes. Is there a way to make the timer smart so if the function is already being executed then it should skip that cycle and come back 60 seconds later and if again it is in execution then again skip and come back 60 seconds later.
CodePudding user response:
The modern and most clean way to do this is using Microsofts new Period Timer:
var timer = new PeriodicTimer(TimeSpan.FromSeconds(n));
while (await timer.WaitForNextTickAsync())
{
//Business logic
}
If you need to abort such a ticker, you can pass a cancellation token to the WaitForNextTickAsync method.
If you need more granularity (like "always at 10 am", use something like https://github.com/HangfireIO/Cronos
CodePudding user response:
If you don't need precision timing you can use a Thread and use DateTime
DateTime nextRunTime = DateTime.UtcNow;
bool BackgroundProcessRunning = true;
void ThreadFunction ()
{
while ( BackgroundProcessRunning )
{
if ( nextRunTime < DateTime.UtcNow )
{
// do stuff
DoStuffForALongTime();
// stuff complete
nextRunTime = DateTime.UtcNow.AddSeconds(60);
}
Thread.Sleep(1);
}
}
Of course you'll still need to kick off the thread and close it correctly when your program is finished, Threading Guide
CodePudding user response:
You can use a Stopwatch inside a loop: start the stopwatch, after 60 second call the function, reset the stopwatch, start the loop again.