20
Jul
2022
2022
Task Scheduler in Asp.Net core
Task Scheduler
Task schedulers are basically used to run some piece of codes at regular intervals so they can pe called recurring jobs. So for creating task scheduler in asp.net core following these steps
So, first of all we have to take a new asp.net core project application and add one new class SchedulerService .
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; namespace SchedulerService.Models { public class SchedulerService : IHostedService, IDisposable { private int executionCount = 0; private System.Threading.Timer _timerNotification; public IConfiguration _iconfiguration; private readonly IServiceScopeFactory _serviceScopeFactory; private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _env; public SchedulerService(IServiceScopeFactory serviceScopeFactory, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, IConfiguration iconfiguration) { _serviceScopeFactory = serviceScopeFactory; _env = env; _iconfiguration = iconfiguration; } public Task StartAsync(CancellationToken stoppingToken) { _timerNotification = new Timer(RunJob, null, TimeSpan.Zero, TimeSpan.FromMinutes(1)); /*Set Interval time here*/ return Task.CompletedTask; } private void RunJob(object state) { using (var scrope = _serviceScopeFactory.CreateScope()) { try { // var store = scrope.ServiceProvider.GetService<IStoreRepo>(); /* You can access any interface or service like this here*/ //store.GetAll(); /* You can access any interface or service method like this here*/ /* Place your code here which you want to schedule on regular intervals */ } catch (Exception ex) { } Interlocked.Increment(ref executionCount); } } public Task StopAsync(CancellationToken stoppingToken) { _timerNotification?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timerNotification?.Dispose(); } } }
In the RunJob you can write the code that you want to execute at regular intervals. You can change the time interval according to your requirement. Now you have to add the service in startup.cs inside ConfigureServices method.
services.AddHostedService<SchedulerService.Models.SchedulerService>();
Now run the application and the RunJob method will run after the given interval.This is how you can create task scheduler in asp.net core.