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) {
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);
}
}
}
}
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?