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

问题描述

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

例如

  • ( 30 13 * * * ) 每天 13:30
  • ( 10 17 * * * ) 每天 17:10
  • ( 40 20 * * * ) 每天 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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)