我正在用C#MVC开发一个应用程序,我希望在不同的时间间隔执行多个后台任务.我已经有了一个继承类BackEarth Service的服务.
I already tried following this tutorial,但只有当你只有一项任务时才有效.
您是否需要 for each 任务提供单独的服务?
我正在用C#MVC开发一个应用程序,我希望在不同的时间间隔执行多个后台任务.我已经有了一个继承类BackEarth Service的服务.
I already tried following this tutorial,但只有当你只有一项任务时才有效.
您是否需要 for each 任务提供单独的服务?
您是否需要 for each 任务提供单独的服务?
这里有多个选项:
官方文档显示了创建Timed background tasks的选项:
public class TimedHostedService : IHostedService, IDisposable
{
private int executionCount = 0;
private readonly ILogger<TimedHostedService> _logger;
private Timer? _timer = null;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object? state)
{
var count = Interlocked.Increment(ref executionCount);
_logger.LogInformation(
"Timed Hosted Service is working. Count: {Count}", count);
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
您可以将此方法与多个计时器一起使用.
您可以只启动ExecuteAsync
个任务中的几个任务:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.WhenAll(Job1(stoppingToken), Job2(stoppingToken));
}
public async Task Job1(CancellationToken stoppingToken)
{
using PeriodicTimer timer = new PeriodicTimer(period1);
while (
!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
Console.WriteLine("Work1");
}
}
public async Task Job2(CancellationToken stoppingToken)
{
using PeriodicTimer timer = new PeriodicTimer(period2);
while (
!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
Console.WriteLine("Work2");
}
}
使用不同的托管服务,每个任务一个(本例中是我个人的转到选项)
还可以考虑更换一些调度库/框架,如Hangfire或Quartz.NET