DEV Community

Cover image for Implement a Time-based Service in .NET 8 using IHostedService Interface🔍

Implement a Time-based Service in .NET 8 using IHostedService Interface🔍

Kaustubh Joshi on December 26, 2024

đź‘“ Introduction Just like we have setInterval() in JavaScript, .NET 8 provides a very helpful interface known as IHostedService in order ...
Collapse
 
govind_prajapati_3707ef68 profile image
Govind Prajapati

Nice.

Collapse
 
elpidaguy profile image
Kaustubh Joshi

Thanks!!

Collapse
 
peter_truchly_4fce0874fd5 profile image
Peter Truchly

Nice tutorial. Did you consider using Quartz.NET?

Collapse
 
elpidaguy profile image
Kaustubh Joshi

Thank you!!!
And no, I have not given Quartz a shot yet.

Do you recommend using it? :)

Collapse
 
peter_truchly_4fce0874fd5 profile image
Peter Truchly

It is quite popular for a long time, I know it from enterprise Java world. Personally, I prefer minimalism whenever it is enough (like with Timer), Quartz is really an enterprise way how to schedule something :D, just a taste of configuration expressions:

0 0 6,19 ? * * = 6:00 AM and 7:00 PM every day.
0 0/30 8-10 ? * * = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
0 0 9-17 * * MON-FRI = on the hour nine-to-five weekdays.

It could be a good topic for another article though.

Thread Thread
 
elpidaguy profile image
Kaustubh Joshi • Edited

Awesome!!! I need to give it a try now, very clean syntax, like cron jobs. Thanks again.

Collapse
 
mrunal_kulkarni_579fcc30c profile image
MRUNAL KULKARNI

Nice

Collapse
 
elpidaguy profile image
Kaustubh Joshi

Thank you :)

Collapse
 
abhay_malviya_72c651605ac profile image
Abhay Malviya

Good topic

Collapse
 
elpidaguy profile image
Kaustubh Joshi

Thank you Abhay!!

Collapse
 
mihir_patel_9938b0385ea07 profile image
Mihir Patel

Can we run this on a recurring basis, specifically every Monday at midnight?

Collapse
 
elpidaguy profile image
Kaustubh Joshi

Hello Mihir,

This Interface should solve your issue of running some logic on recurring manner.
But as far as this code goes, you cannot specify the day and time directly.

For example,
I cannot tell the code that, please run the DoWork logic specifically on Monday at 12AM IST.

Instead,
I can add the Timer Due Period as,
new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromDays(7));

This will run every 7 days immediately after you deploy it.
Although, here you will need to deploy it on Monday 12AM, so that it will run recurrently every 7 days.

You can also add offset time as,
new Timer(DoWork, null, TimeSpan.FromHours(5), TimeSpan.FromDays(7));
So, you can deploy it 5 hours before 12 AM and then it will keep running it after every 7 Days.

You can always create a custom TimeSpan event by subtracting the current time with your desired time, i.e. Monday 12AM logically.

Please feel free to experiment more with examples to get your desired output.
Hope this helps!!!