How to run multiple cron expression in c# background service

866 Views Asked by At

I am using BackgroundService for my tasks and i would like to run different tasks at different times for example i have a task which should run once a day and i have come up with this cron expression "@daily" which is ok for my first task. But for my second task which should run multiple times a day i need multiple cron expressions

for example

  • ( 30 13 * * * ) daily at 13:30
  • ( 10 17 * * * ) daily at 17:10
  • ( 40 20 * * * ) daily at 20:40
  • ( 15 22 * * * ) daily at 22:15

and the classes which i use looks like this

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

            };
        }


    }

and the actual class which contains the actual task.

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;
    }
}

instead of executing a single cron expression i want to run multiple cron expressions after one another at a daily basis. Maybe CronTrigger can help but i dont know where and how can i use CronTrigger in my Classes.

0

There are 0 best solutions below