In this article, we are going to understand about Hosting a Background Task or Job inside of an Asp.NetCore application.
Hosted BackGround Task Workflow:
To create a background job or task in an Asp.Net core application then the class should inherit the 'Microsoft.Extension.Hosting.BackgroundService'. The 'Microsoft.Extension.Hosting.BackgroundService' is an abstract class that contains overridable methods like 'StopAsync', 'ExecuteAsync'.
- StopAsync - gets executed once our normal Asp.Net core application stops.
- ExecuteAsync - gets executed after the 'StartAsync' method and it is in an abstract method which means it must be implemented in our background job class. Here we can write logic like to run a particular job at regular intervals until the Asp.Net core application stops running.
When To Use? :
So Hosted Background job can be used in cases like:
- 1. If our Asp.Net core generates some files and we have to delete them at regular intervals of time.
- 2. If our Background job and Asp.Net core application share common or reusable code.
Create A .NET 6 Web API Application:
Let's create a .Net6 Web API sample application to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor.
CLI command
dotnet new webapi -o Your_Project_Name
dotnet new webapi -o Your_Project_Name
Add Background Task:
Let's create our background task which starts along with our Aps.Net Core Web API. So let's create a file like 'Job/TimerJob.cs'.
Job/TimerJob.cs:
namespace Dot6.BGJob.Job; public class TimerJob : BackgroundService { private Timer _timer; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { Console.WriteLine("Background job starts along with api application on start"); _timer = new Timer(Dowork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); } private void Dowork(object? state) { Console.WriteLine("dowork tasks runs for every "); } public override async Task StopAsync(CancellationToken stoppingToken) { Console.WriteLine("Background job stops along with api application on stop"); } }
- Here 'TimerJob' is our background job Hosted with Asp.NetCore Application.
- (Line: 3) The 'TimeJob' class inherited the 'Microsoft.Extensions.Hosting.BackgroundService'.
- (Line: 4) Declared a timer variable.
- (Line: 7) The 'ExecuteAsync' is an abstract method that must be implemented in our background task. So on Asp.NetCore API starts our background job 'ExectueAsync' method gets triggered.
- (Line: 10) Setting timer to run 'Dowork' method to invoke for every 5 seconds until the Asp.NetCore Applications stops.
- (Line: 13-16) Here is our main job logic need to be implemented. In real applications, jobs like 'deleting files' or 'any CPU-related works' logic should be implemented.
- (Line: 18-21) The 'StopAsync' executed on stopping of the Asp.NetCore API application this method can be used for logging information about the when job stoped.
Program.cs:
builder.Services.AddHostedService<TimerJob>();Now run the application, we can see an initial log of the 'ExecuteAsync' method.
Now we can observe for every '5' seconds our job getts runs that can be observed with our logs.
Now stop the application we can observe that the 'StopAsync' method was executed.
Consume Scoped Service:
We can utilize scoped service of the Asp.NetCore application into the background job.
Let's create a sample service like 'ITestServices.cs', 'TestService.cs'.
Service/ITestService.cs:
namespace Dot6.BGJob.Services; public interface ITestService { void TestWork(); }Service/TestService.cs:
namespace Dot6.BGJob.Services; public class TestService:ITestService { public void TestWork() { Console.WriteLine("Test work method"); } }Register our 'ITestService', 'TestService' at scoped level in 'Program.cs'
Program.cs:
builder.Services.AddScoped<ITestService, TestService>();Now let's try to update our background job to consume the scoped service(eg: ITestService). Inject the 'IServiceProvider' in the constructor of our 'TimerJob.cs'.
Job/TimerJob.cs:(Update Dowork Method)
private void Dowork(object? state) { using (var scope = _serviceProvider.CreateScope()) { var testService = scope.ServiceProvider.GetRequiredService<ITestService>(); testService.TestWork(); } }Here we consume the scoped service(ITestService) into our background job.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on Background tasks with hosted service in Asp.NetCore. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment