hostedservice that can run periodically
$ dotnet add package Samhammer.TimedHostedServiceThis package provides a hosted service that can run periodically.
The concept is from this documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio
Implement a class that inherits TimedHostedService.
public class MyHostedService : TimedHostedService<IMyService>
{
protected override TimeSpan StartDelay => TimeSpan.FromSeconds(3);
protected override TimeSpan ExecutionInterval => TimeSpan.FromDays(1);
public MyHostedService(ILogger<MyHostedService> logger, IServiceScopeFactory services)
: base(logger, services)
{
}
protected override Task RunScoped(IMyService myService)
{
myService.DoSomething();
return Task.CompletedTask;
}
}
Register the hosted service in startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<MyHostedService>()
}
Possible configurations:
Possible hook points:
Note: