Simon Simon - 2 months ago 14x
C# Question

Timer run every 5th minute

How can I run some function every 5th minute? Example: I want run

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:

var timer = new Timer(TimerTick, null, TimeSpan.Zero, new TimeSpan(0, 0, 0, 1));

int lastMinute = 1;

void TimerTick(object state)
    var minute = DateTime.Now.Minutes;
    if (minute != lastMinute && minute % 5 == 0)
        lastMinute = minute;
        //do stuff

This might look somewhat clumsy and inefficient since it has to call every second, but the actual number of CPU cycles that get used to perform the check once a second is totally negligible on virtually any hardware.

(Sorry if the code isn't 100% correct; I don't have an IDE on me right now.