Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Start Task at specific time

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading