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.
ASP.NET Core support to run background tasks with hosted services, see this doc. It has an interface named IHostedService for user-defined Hosted services. The interface defines two methods for objects that are managed by the host:
You can also inherit the abstract class BackgroundService by implementing the ExecuteAsync method like this:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.Register(() =>
_logger.LogDebug($"Background task is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogDebug($"Background task doing work.");
DoTask();
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
After defining your hosted services, you need to add them to ServiceCollection as singleton. Then these background tasks will be running within the asp.net core application.
Consider to use https://github.com/fluentscheduler/FluentScheduler.
Example of job is very simple
JobManager.AddJob(() => Console.WriteLine("My job!"),
(s) => s.ToRunEvery(5).Seconds());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With