asp.net 如何在特定时间间隔内运行多个后台任务?

jucafojl  于 6个月前  发布在  .NET
关注(0)|答案(1)|浏览(75)

我正在用C# MVC开发一个应用程序,我想在不同的时间间隔执行多个后台任务。我已经有了一个继承BackgroundService类的服务。
I already tried following this tutorial,但只有当你只有一个任务时才有效。
您是否需要为每项任务提供单独的服务?

w6mmgewl

w6mmgewl1#

您是否需要为每项任务提供单独的服务?
这里有多种选择:

  • 官方文档显示了创建定时后台任务的选项:
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");
     }
}

  • 使用不同的托管服务,每个任务一个(在这种情况下,我个人选择去)
  • 还可以考虑切换一些调度库/框架,如HangfireQuartz.NET

相关问题