I have an class which derives from IHostedService
. In here I have the override method StartAsync
as shown below:
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoSomething, null, offset, TimeSpan.FromHours(1));
return Task.CompletedTask;
}
In here I have the variable offset which is of the TimeSpan class.
What I need:
I need to calculate the offset in such way that the task "DoSomething" will be executed every start of an hour, like: 10:00, 13:00, 21:00 or 00:00. So this offset needs to be in minutes.
Example :
Let’s say the application starts running at 13:48PM
, the correct offset would be 12 minutes and the next hour would be 14
.
My question:
How would I calculate the offset which is in minutes until next hour ?
>Solution :
something like
var minutes = (DateTime.Today.AddHours(DateTime.Now.Hour+1)-DateTime.Now).TotalMinutes
should do the trick