
Task timerTask = RunPeriodically(sendRequest, TimeSpan.FromMinutes(5), tokenSource.Token) It can be called like this: CancellationTokenSource tokenSource = new CancellationTokenSource() Then that can be implemented very easily, like this: async Task RunPeriodically(Action action, TimeSpan interval, CancellationToken token) it's not that important that it run exactly on five-minute divisions of the hour). Then, let's assume that the basic requirement is to run it roughly every five minutes (i.e.
#SET TIMER FOR 5 MINUTES HOW TO#
Also, I differ a little on the specifics of the implementation, such as how to manage the delay computation and how to round the current time to the next five minute interval.įirst, let's assume the sendRequest() method returns void and has no parameters. However, IMHO with modern C# it is now better to use the Task-based API with async and await. The answer posted six years ago is useful.

You can probably get away with a value smaller than one second but I'll leave that to you. 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. Var Timer = new Timer(callback, null, timeToStart, TimeSpan.FromMinutes(5)) TimeSpan tolerance = TimeSpan.FromSeconds(1) TimeSpan timeToStart = nearestOnFiveMinutes.Subtract(now) Int additionalMinutes = 5 - now.Minute % 5 Note that you'll need to keep your application alive somehow (e.g., run it as a service).Īs for how to make sure that it runs at hh:mm where mm % 5 = 0, you can do the following. You can use the second parameter to pass state to the callback.

You can specify a method to call periodically.Įxample: Timer timer = new Timer(Callback, null, TimeSpan.Zero, TimeSpan.FromMinutes(5)) Ĭonsole.WriteLine("The current time is ", DateTime.Now)
