Home » c# » c# – Asp.Net – Scheduled Task using IHostedService-Exceptionshub

c# – Asp.Net – Scheduled Task using IHostedService-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


I’m working on an ASP.NET web application written in C# and hosted in an Azure virtual machine using IIS 10 as a web server. I have to schedule a background task to run once a day. To achieve this I created the following DailyTask class:

public class DailyTask : IHostedService {

    public Task StartAsync(CancellationToken cancellationToken) {
        Task.Run(TaskRoutine, cancellationToken);
        return Task.CompletedTask;

    public Task StopAsync(CancellationToken cancellationToken) {
        return null;

    public Task TaskRoutine() {
        while (true) {
            try {
                /* ... */

                DateTime nextStop = DateTime.Now.AddDays(1);
                var timeToWait = nextStop - DateTime.Now;
                var millisToWait = timeToWait.TotalMilliseconds;

            catch (Exception e) {

To start this task I added the following statement in my Startup class:

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        /* ... */
        services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, HiddenUserCleaner>();
        /* ... */

After a deploy on my test server, I observed that this solution works fine. But is it reliable? Can there be problems if used in production?

How to&Answers:

It’s not safe. Take a look at the guide here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio

If the app shuts down unexpectedly (for example, the app’s process fails), StopAsync might not be called. Therefore, any methods called or operations conducted in StopAsync might not occur.

It’s not the case exactly, but it assumes that the application can be restarted. Same thing goes with application pool which restarts occasionally.

Overall, this will not assure that it will run daily. If the application restarts frequently for whatever reason, it could be that it never runs.

The same is true with libraries like hangfire.

Other solutions could be web jobs, or you could check if it has executed today by using some kind of persistence like a database that stores the last execution time and the IHostingService will check every some time and on startup whether or not it should execute the background job and act accordingly.