title: Asp.Net - Scheduled Task using IHostedService
body: <p>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 <code>DailyTask</code> class:</p>
  
  <pre><code>public class DailyTask : IHostedService {
  
      public Task StartAsync(CancellationToken cancellationToken) {
          Debug.WriteLine("start");
          Task.Run(TaskRoutine, cancellationToken);
          return Task.CompletedTask;
      }
  
      public Task StopAsync(CancellationToken cancellationToken) {
          Debug.WriteLine("stop");
          return null;
      }
  
      public Task TaskRoutine() {
          while (true) {
              try {
                  /* ... */
  
                  DateTime nextStop = DateTime.Now.AddDays(1);
                  var timeToWait = nextStop - DateTime.Now;
                  var millisToWait = timeToWait.TotalMilliseconds;
                  Thread.Sleep((int)millisToWait);
              }
  
              catch (Exception e) {
                  Debug.WriteLine(e);
              }
          }
      }
  }
  </code></pre>
  
  <p>To start this task I added the following statement in my <code>Startup</code> class:</p>
  
  <pre><code>public class Startup {
      public void ConfigureServices(IServiceCollection services) {
          /* ... */
          services.AddSingleton&lt;Microsoft.Extensions.Hosting.IHostedService, HiddenUserCleaner&gt;();
          /* ... */
      }
  }
  </code></pre>
  
  <p>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?</p>