Running background tasks periodically in an ASP.NET Core RC2 application

aw1975 picture aw1975 · May 31, 2016 · Viewed 9k times · Source

I'm working on an ASP.NET Core RC2 application. There is a requirement for this application to periodically invoke certain tasks, such as sending emails or invoking specific business logic.

I'm aware that there are third-party libraries such as Hangfire or Quartz.NET that provide this scheduling functionality out-of-the-box. However I don't think either of these currently support ASP.NET Core RC2. Are there are any other options available that are compatible with ASP.NET Core RC2?

If not, I guess a possible option is to use one of these third-party libraries from within a separate windows service, which could then target a supported version of .NET. This service could then periodically make requests to the ASP.NET application through its Web API in order to invoke the tasks.

However I'd prefer not to have a separate service as it increases the number of moving parts and complicates the deployment of our application.

Answer

James picture James · Jan 17, 2017

A manual approach:

  • Create a Service containing the long-running code, preferably async
  • Add a while loop to the service with pausing (also preferably async)
  • Call the long running method of the service class in a new thread with Task.Run(() => ... or in the thread pool (or in a legacy Thread).
  • Create an instance of the class in Startup.cs
  • Use services.AddSingleton(MyServiceInstance); in Configure(... in Startup.cs