Bug
Bug

Reputation: 942

.NET Core Delay vs Schedule

I am trying to run a Background Scheduled Task (in a Console App) after x minutes and I can easily achieve it using Task.Delay. But, what is the advantaged of using a Task Scheduler?

EDIT: BTW, I do not have any special requirements, just want to understand why one is better than the other. A Task Scheduler requires a lot of code, so why is worth the Scheduler Task?

This is an example that I am following: https://blog.maartenballiauw.be/post/2017/08/01/building-a-scheduled-cache-updater-in-aspnet-core-2.html

Upvotes: 0

Views: 515

Answers (1)

ttugates
ttugates

Reputation: 6271

Task.Delay does what it says on the tin and thats about it.

The IScheduledTask/IHostedService implementation provides a couple of features.

  1. You have a self contained class that can have dependencies injected to run the code in its own scope.
  2. IHostedService provides a mechanism for graceful shutdown. In an ASP.NET application, the app can be recycled, you don't have a guarantee that the code you called Task.Delay(1000*60) on will execute. With IScheduledTask solution, you implement the StopAsync() method to provide a graceful cancellation of the Task. You can also configure the Host Configuration Shutdown Timeout.

Your question is regarding a console application and it appears from here as of .Net Core 2.1 the WebHost will be replaced with Generic Host and as such will no longer pertain specifically to ASP.NET.

Tangent: I have a related question ASP.Net Core 2.0 Shutdown Timeout, what issues can I expect using a very long time out of 2 min? <- I have not had any issues in Production with a time out of 2 min.

Upvotes: 1

Related Questions