如何在c#后台服务中运行多个cron表达式

如何在c#后台服务中运行多个cron表达式,c#,cron,background-service,crontrigger,C#,Cron,Background Service,Crontrigger,我正在使用BackgroundService处理我的任务,我希望在不同的时间运行不同的任务。例如,我有一个任务应该每天运行一次,我已经想出了一个cron表达式“@daily”,这对于我的第一个任务来说是可以的。但是对于我的第二个任务,它应该一天运行多次,我需要多个cron表达式 比如说 (30 13***)每天13:30 (10 17***)每天17:10 (40***)每天20:40 (15 22***)每天22:15 我使用的类是这样的 public abstract class Bac

我正在使用BackgroundService处理我的任务,我希望在不同的时间运行不同的任务。例如,我有一个任务应该每天运行一次,我已经想出了一个cron表达式“@daily”,这对于我的第一个任务来说是可以的。但是对于我的第二个任务,它应该一天运行多次,我需要多个cron表达式

比如说

  • (30 13***)每天13:30
  • (10 17***)每天17:10
  • (40***)每天20:40
  • (15 22***)每天22:15
我使用的类是这样的

public abstract class BackgroundService : IHostedService
{
    private Task _executingTask;
    private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();
    public virtual Task StartAsync(CancellationToken cancellationToken)
    {
        _executingTask = ExecuteAsync(_stoppingCts.Token);

        if (_executingTask.IsCompleted)
        {
            return _executingTask;
        }

        return Task.CompletedTask;
    }

    public virtual async Task StopAsync(CancellationToken cancellationToken)
    {
        if (_executingTask == null)
        {
            return;
        }

        try
        {
            _stoppingCts.Cancel();
        }
        finally
        {
            await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
        }
    }

    protected virtual async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        do
        {
            await Process();

            await Task.Delay(5000, stoppingToken);

        } while (!stoppingToken.IsCancellationRequested);
    }

    protected abstract Task Process();

}

public abstract class ScopedProcessor : BackgroundService
{
    private IServiceScopeFactory _serviceScopeFactory;

    public ScopedProcessor(IServiceScopeFactory serviceScopeFactory) : base()
    {
        _serviceScopeFactory = serviceScopeFactory;
    }
    protected override async Task Process()
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            await ProcessInScope(scope.ServiceProvider);
        }
    }

    public abstract Task ProcessInScope(IServiceProvider scopeServiceProvider);
}

public abstract class ScheduledProcessor : ScopedProcessor
    {
        private CrontabSchedule _schedule;
        private DateTime _nextRun;

        protected abstract string Schedule { get; }

        public ScheduledProcessor(IServiceScopeFactory serviceScopeFactory) : base(serviceScopeFactory)
        {
            _schedule = CrontabSchedule.Parse(Schedule);
            _nextRun = _schedule.GetNextOccurrence(DateTime.Now);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                var now = DateTime.Now;

                if (now > _nextRun)
                {
                    await Process();
                     
                     // for the first task which should run daily is ok but
                     // for my second task i want to run the multiple cron expressions after 
                     // one another 
                    _nextRun = _schedule.GetNextOccurrence(DateTime.Now);
                }

                await Task.Delay(5000, stoppingToken); // 5 seconds delay

            };
        }


    }
以及包含实际任务的实际类

public class MyTask : ScheduledProcessor
{


    public MyTask(IServiceScopeFactory serviceScopeFactory) : base(serviceScopeFactory)
    {

    }
    
    // cron expression
    protected override string Schedule => "*/1 * * * *"; // every 1 min for testing purpose
    
    // actual task
    public override Task ProcessInScope(IServiceProvider scopeServiceProvider)
    {
        Console.WriteLine("MyTask Running " + DateTime.Now.ToShortTimeString());
        // do other work
        return Task.CompletedTask;
    }
}

我不想执行单个cron表达式,而是希望每天一个接一个地运行多个cron表达式。也许CronTrigger可以提供帮助,但我不知道在我的类中在何处以及如何使用CronTrigger。

如果您要在Azure中托管此功能,Azure函数已经为您完成了所有这一切。感谢您的快速回复。问题是上面的cron表达式不是常数,它可以每天更改,但在小时或分钟内会有一点差异。这就是为什么我认为在Azure中每天手动更改它不是一个好主意。@Faisal…您找到解决方案了吗?