| | | 1 | | using Elsa.Common; |
| | | 2 | | using Elsa.Mediator.Contracts; |
| | | 3 | | using Elsa.Scheduling.Commands; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | using Timer = System.Timers.Timer; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Scheduling.ScheduledTasks; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// A scheduled recurring task. |
| | | 12 | | /// </summary> |
| | | 13 | | public class ScheduledRecurringTask : IScheduledTask, IDisposable |
| | | 14 | | { |
| | | 15 | | private readonly ITask _task; |
| | | 16 | | private readonly ISystemClock _systemClock; |
| | | 17 | | private readonly IServiceScopeFactory _scopeFactory; |
| | | 18 | | private readonly ILogger<ScheduledRecurringTask> _logger; |
| | | 19 | | private readonly TimeSpan _interval; |
| | | 20 | | private readonly CancellationTokenSource _cancellationTokenSource; |
| | 8 | 21 | | private readonly SemaphoreSlim _executionSemaphore = new(1, 1); |
| | | 22 | | private DateTimeOffset _startAt; |
| | | 23 | | private Timer? _timer; |
| | | 24 | | private bool _executing; |
| | | 25 | | private bool _cancellationRequested; |
| | | 26 | | private bool _disposed; |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Initializes a new instance of <see cref="ScheduledRecurringTask"/>. |
| | | 30 | | /// </summary> |
| | 8 | 31 | | public ScheduledRecurringTask(ITask task, DateTimeOffset startAt, TimeSpan interval, ISystemClock systemClock, IServ |
| | | 32 | | { |
| | 8 | 33 | | _task = task; |
| | 8 | 34 | | _systemClock = systemClock; |
| | 8 | 35 | | _scopeFactory = scopeFactory; |
| | 8 | 36 | | _logger = logger; |
| | 8 | 37 | | _startAt = startAt; |
| | 8 | 38 | | _interval = interval; |
| | 8 | 39 | | _cancellationTokenSource = new(); |
| | | 40 | | |
| | 8 | 41 | | Schedule(); |
| | 8 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <inheritdoc /> |
| | | 45 | | public void Cancel() |
| | | 46 | | { |
| | 1 | 47 | | _timer?.Dispose(); |
| | | 48 | | |
| | 1 | 49 | | if (_executing) |
| | | 50 | | { |
| | 0 | 51 | | _cancellationRequested = true; |
| | 0 | 52 | | return; |
| | | 53 | | } |
| | | 54 | | |
| | 1 | 55 | | _cancellationTokenSource.Cancel(); |
| | 1 | 56 | | } |
| | | 57 | | |
| | | 58 | | private void Schedule() |
| | | 59 | | { |
| | 8 | 60 | | var startAt = _startAt; |
| | 8 | 61 | | var adjusted = false; |
| | | 62 | | |
| | | 63 | | while (true) |
| | | 64 | | { |
| | 13 | 65 | | var now = _systemClock.UtcNow; |
| | 13 | 66 | | var delay = startAt - now; |
| | | 67 | | |
| | 13 | 68 | | if (!adjusted && delay <= TimeSpan.Zero) |
| | | 69 | | { |
| | 5 | 70 | | adjusted = true; |
| | 5 | 71 | | continue; |
| | | 72 | | } |
| | | 73 | | |
| | 8 | 74 | | SetupTimer(delay); |
| | | 75 | | break; |
| | | 76 | | } |
| | 8 | 77 | | } |
| | | 78 | | |
| | | 79 | | private void SetupTimer(TimeSpan delay) |
| | | 80 | | { |
| | | 81 | | // Handle edge cases where delay is zero or negative (e.g., due to clock drift, fast execution, or time alignmen |
| | | 82 | | // Instead of silently returning, use a minimum delay to ensure the timer fires and workflow continues schedulin |
| | 8 | 83 | | if (delay <= TimeSpan.Zero) |
| | | 84 | | { |
| | 5 | 85 | | _logger.LogWarning("Calculated delay is {Delay} which is not positive. Using minimum delay of 1ms to ensure |
| | 5 | 86 | | delay = TimeSpan.FromMilliseconds(1); |
| | | 87 | | } |
| | | 88 | | |
| | 8 | 89 | | _timer = new(delay.TotalMilliseconds) |
| | 8 | 90 | | { |
| | 8 | 91 | | Enabled = true |
| | 8 | 92 | | }; |
| | | 93 | | |
| | 8 | 94 | | _timer.Elapsed += async (_, _) => |
| | 8 | 95 | | { |
| | 0 | 96 | | _timer?.Dispose(); |
| | 0 | 97 | | _timer = null; |
| | 8 | 98 | | |
| | 8 | 99 | | // Check if disposed before proceeding |
| | 0 | 100 | | if (_disposed) return; |
| | 8 | 101 | | |
| | 0 | 102 | | _startAt = _systemClock.UtcNow + _interval; |
| | 8 | 103 | | |
| | 0 | 104 | | using var scope = _scopeFactory.CreateScope(); |
| | 0 | 105 | | var commandSender = scope.ServiceProvider.GetRequiredService<ICommandSender>(); |
| | 8 | 106 | | |
| | 8 | 107 | | // Check disposed again before accessing CancellationTokenSource |
| | 0 | 108 | | if (_disposed) return; |
| | 8 | 109 | | |
| | 0 | 110 | | var cancellationToken = _cancellationTokenSource.Token; |
| | 0 | 111 | | if (!cancellationToken.IsCancellationRequested) |
| | 8 | 112 | | { |
| | 0 | 113 | | var acquired = false; |
| | 8 | 114 | | try |
| | 8 | 115 | | { |
| | 0 | 116 | | acquired = await _executionSemaphore.WaitAsync(0, cancellationToken); |
| | 0 | 117 | | if (!acquired) return; |
| | 0 | 118 | | _executing = true; |
| | 0 | 119 | | await commandSender.SendAsync(new RunScheduledTask(_task), cancellationToken); |
| | 8 | 120 | | |
| | 0 | 121 | | if (_cancellationRequested) |
| | 8 | 122 | | { |
| | 0 | 123 | | _cancellationRequested = false; |
| | 0 | 124 | | _cancellationTokenSource.Cancel(); |
| | 8 | 125 | | } |
| | 0 | 126 | | } |
| | 0 | 127 | | catch (Exception e) |
| | 8 | 128 | | { |
| | 0 | 129 | | _logger.LogError(e, "Error executing scheduled task"); |
| | 0 | 130 | | } |
| | 8 | 131 | | finally |
| | 8 | 132 | | { |
| | 0 | 133 | | _executing = false; |
| | 0 | 134 | | if (acquired && !_disposed) |
| | 0 | 135 | | _executionSemaphore.Release(); |
| | 8 | 136 | | } |
| | 8 | 137 | | } |
| | 8 | 138 | | |
| | 0 | 139 | | if (!cancellationToken.IsCancellationRequested && !_disposed) |
| | 0 | 140 | | Schedule(); |
| | 8 | 141 | | }; |
| | 8 | 142 | | } |
| | | 143 | | |
| | | 144 | | void IDisposable.Dispose() |
| | | 145 | | { |
| | 11 | 146 | | _disposed = true; |
| | 11 | 147 | | _timer?.Dispose(); |
| | 11 | 148 | | _cancellationTokenSource.Dispose(); |
| | 11 | 149 | | _executionSemaphore.Dispose(); |
| | 11 | 150 | | } |
| | | 151 | | } |