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

如何解决如何在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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?