Background jobs are an alternative to synchronous processing, it's an approach to lighten the main thread and offload tasks to a secondary thread.
To explain the concept let's imagine a web application dedicated to video processing which's obviously a heavy task, so the main application get the request from a third party application or the browser, then it delegates the task to a background job, but the main thread can't wait for the response cause it will take a considerable amount of time to finish the task from the worker job, so to free the main application thread the communication is established asynchronously by creating a message queue bridge between the application and background job, so the main application place the task in queue and then move on to get more processing request, and the background job can treat the requests at it's own speed.
The main criteria to decide whether a task can be executed in background or not is by asking yourself if the task need the interaction with user while in execution or the user is obliged to wait for the job result, if the answer is yes so the backgound job implementation can be inapropriate in this case.
There's two type of background job triggers :
- Event driven trigger : the background job is launched in parallel with the main application when a start event is raised.
- Schedule driven trigger : in this approach the task is invoked periodically based on a timer.
- In the .Net core platform we can build background jobs by implementing IHostedService interface.
In the code above The StartAsync method is triggered when our service kicks off, it's a setup method where we configure and launch the background job to do the work.
On the other side StopAsync is called when we stop our background service so we can do whatever we need to dispose used resources.
The .Net hosted services are tied to the hosted service, that means
they are deployed with the main application within the same host
We will create a simple hosted service which will simply print Hello World every 10 seconds, and inject it as hosted service to ASP .Net Api application.
1. Implemente IHostedService
- In the code above we decalred an instance of a Timer object which will be configured to execute a callback method periodically.
The Timer is an object that raises an event after a number of milliseconds elapsed. You can configure the Timer object to raise the event just once or repeatedly.
- In the StartAsync method we configured the timer to execute
PrintHelloWord()periodically after each 10 seconds, in the other side StopAsync method is used to stop the timer callbacks when the job is turned off.
2. Configure API by adding our hosted service
- We need to add our hosted service to
ConfigureServicesmethod in startup.cs :
- And we are done if we start our api now MyHostedService will kicks off, check the Debug output to see the result 😉.
- The hosted services are tied to the main host web application, so when we scale horizontally our web application it involves the creation of new job instance. So we should be aware of that and avoid using hosted services in cases where jobs will compete with each others and lead to unwanted behaviours.