How can I run some function every 5th minute? Example: I want run sendRequest()
only at time 14:00, 14:05, 14:10 etc.
I would like to do it programmatically, in C#. The application is a Windows service.
Use System.Threading.Timer
. You can specify a method to call periodically.
Example:
Timer timer = new Timer(Callback, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));
public void Callback(object state) {
Console.WriteLine("The current time is {0}", DateTime.Now);
}
You can use the second parameter to pass state to the callback.
Note that you'll need to keep your application alive somehow (e.g., run it as a service).
As for how to make sure that it runs at hh:mm
where mm % 5 == 0
, you can do the following.
DateTime now = DateTime.Now;
int additionalMinutes = 5 - now.Minute % 5;
if(additionalMinutes == 0) {
additionalMinutes = 5;
}
var nearestOnFiveMinutes = new DateTime(
now.Year,
now.Month,
now.Day,
now.Hour,
now.Minute,
0
).AddMinutes(additionalMinutes);
TimeSpan timeToStart = nearestOnFiveMinutes.Subtract(now);
TimeSpan tolerance = TimeSpan.FromSeconds(1);
if (timeToStart < tolerance) {
timeToStart = TimeSpan.Zero;
}
var Timer = new Timer(callback, null, timeToStart, TimeSpan.FromMinutes(5));
Note that the tolerance
is necessary in case this code is executing when now
is very close to the nearest hh:mm
with mm % 5 == 0
. You can probably get away with a value smaller than one second but I'll leave that to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With