Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer run every 5th minute

Tags:

c#

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.

like image 420
Simon Avatar asked Dec 10 '10 14:12

Simon


1 Answers

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.

like image 132
jason Avatar answered Oct 11 '22 21:10

jason