首先,我们需要创建一个基于Timer的后台服务。然后,我们将在Startup.cs中注册他们,以便将它们添加到DI容器中。最后,我们使用IHostedService接口来启动和停止后台任务。
代码示例如下:
1.创建后台服务:
public class MyBackgroundService1 : BackgroundService
{
private readonly ILogger _logger;
public MyBackgroundService1(ILogger logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("MyBackgroundService1 is running.");
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
}
public class MyBackgroundService2 : BackgroundService
{
private readonly ILogger _logger;
public MyBackgroundService2(ILogger logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("MyBackgroundService2 is running.");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
2.注册服务:
public void ConfigureServices(IServiceCollection services)
{
// Add timer based background services
services.AddHostedService();
services.AddHostedService();
}
3.启动和停止服务:
public class MyHostedService : IHostedService
{
private readonly IEnumerable _hostedServices;
public MyHostedService(IEnumerable hostedServices)
{
_hostedServices = hostedServices;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
foreach (var hostedService in _hostedServices)
{
await hostedService.StartAsync(cancellationToken);
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
foreach (var hostedService in _hostedServices.Reverse())
{
await hostedService.StopAsync(cancellationToken);