This 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
- reference this nuget package: https://www.nuget.org/packages/Samhammer.TimedHostedService/
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:
- ExecutionInterval: How often the job ticks after starting (default: 60 seconds)
- StartDelay: Delay the first tick for a specific time after starting (default: 0)
- OnlySingleInstance: If the last tick is still no other tick is started even if the executionInterval is over (default: false)
Possible hook points:
- RunScoped: Execute your logic here (mandatory)
- OnStartup: Is called before the timer starts ticking (optional)
- OnRunSuccessful: Is executed after the current tick is over (optional)
- OnError: Can be used to handle errors that occur within a running tick
Note:
- Errors inside "ExecutionInterval" are catched and can be handled with "OnError"
- "RunScoped" is running in it's ioc scope. The other hook points are outside of this scope.
- Create a tag and let the github action do the publishing for you