HostedServices are a new thing in ASP.NET Core 2.0 and can be used to run tasks in the asynchronously in the background of your application. This can be used to fetch data periodically, do some calculations in the background or some cleanups. This can also be used to send preconfigured emails or whatever you need to do in the background.
HostedServices are basically simple classes, which implements the
HostedService needs to implement a
StartAsync() and a
StopAsync() method. The
StartAsync() is the place where you implement the logic to execute. This method gets executed once immediately after the application starts. The method
StopAsync() on the other hand gets executed just before the application stops. This also means, to start a kind of a scheduled service you need to implement it by your own. You will need to implement a loop which executes the code regularly.
To get a
HostedService executed you need to register it in the ASP.NET Core dependency injection container as a singleton instance:
To see how a hosted service work, I created the next snippet. It writes a log message on start, on stop and every two seconds to the console:
To test this, I simply created a new ASP.NET Core application, placed this snippet inside, register the
HostedService and started the application by calling the next command in the console:
As you can see the log output is written to the console every two seconds.
You can now start to do some more complex thing with the
HostedServices. Be careful with the hosted service, because it runs all in the same application. Don't use to much CPU or memory, this could slow down your application.
For bigger applications I would suggest to move such tasks in a separate application that is specialized to execute background tasks. A separate Docker container, a BackroundWorker on Azure, Azure Functions or something like this. However it should be separated from the main application in that case.