dotnet-labs / ServiceWorkerCronJob

Schedule Cron Jobs using HostedService in ASP.NET Core
MIT License
264 stars 72 forks source link

Crojobs with more than 25days not working #15

Closed DavidStania closed 2 weeks ago

DavidStania commented 1 year ago

This service will fail if the timer-delay is more than 25 days. I need to run a job once a month and the timer throw a unhandled exception

image

Bug-Fix

You should use the system.threading.timer instead .

protected virtual async Task ScheduleJob(CancellationToken cancellationToken)
{
    var next = _expression.GetNextOccurrence(DateTimeOffset.Now, _timeZoneInfo);
    if (next.HasValue)
    {
        var delay = next.Value - DateTimeOffset.Now;
        if (delay.TotalMilliseconds <= 0)   // prevent non-positive values from being passed into Timer
        {
            await ScheduleJob(cancellationToken);
        }
        _timer = new System.Threading.Timer(async (state) =>
        {
            _timer.Dispose();  // reset and dispose timer
            _timer = null;

            if (!cancellationToken.IsCancellationRequested)
            {
                await DoWork(cancellationToken);
            }

            if (!cancellationToken.IsCancellationRequested)
            {
                await ScheduleJob(cancellationToken);    // reschedule next
            }

        }, null, delay, new TimeSpan(0, 0, 0, 0, -1));

    }
    await Task.CompletedTask;
}
changhuixu commented 2 weeks ago

probably can be closed due to #17