| | | 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 task that is scheduled using a given cron expression. |
| | | 12 | | /// </summary> |
| | | 13 | | public class ScheduledCronTask : IScheduledTask, IDisposable |
| | | 14 | | { |
| | | 15 | | private readonly ISystemClock _systemClock; |
| | | 16 | | private readonly ILogger _logger; |
| | | 17 | | private Timer? _timer; |
| | | 18 | | private readonly ITask _task; |
| | | 19 | | private readonly string _cronExpression; |
| | | 20 | | private readonly ICronParser _cronParser; |
| | | 21 | | private readonly IServiceScopeFactory _scopeFactory; |
| | | 22 | | private readonly CancellationTokenSource _cancellationTokenSource; |
| | 8 | 23 | | private readonly SemaphoreSlim _executionSemaphore = new(1, 1); |
| | | 24 | | private bool _executing; |
| | | 25 | | private bool _cancellationRequested; |
| | | 26 | | private bool _disposed; |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Initializes a new instance of <see cref="ScheduledCronTask"/>. |
| | | 30 | | /// </summary> |
| | 8 | 31 | | public ScheduledCronTask(ITask task, string cronExpression, ICronParser cronParser, IServiceScopeFactory scopeFactor |
| | | 32 | | { |
| | 8 | 33 | | _task = task; |
| | 8 | 34 | | _cronExpression = cronExpression; |
| | 8 | 35 | | _cronParser = cronParser; |
| | 8 | 36 | | _scopeFactory = scopeFactory; |
| | 8 | 37 | | _systemClock = systemClock; |
| | 8 | 38 | | _logger = logger; |
| | 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 | | { |
| | 1 | 51 | | _cancellationRequested = true; |
| | 1 | 52 | | return; |
| | | 53 | | } |
| | | 54 | | |
| | 0 | 55 | | _cancellationTokenSource.Cancel(); |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | private void Schedule() |
| | | 59 | | { |
| | 8 | 60 | | var adjusted = false; |
| | | 61 | | |
| | | 62 | | while (true) |
| | | 63 | | { |
| | 12 | 64 | | var now = _systemClock.UtcNow; |
| | 12 | 65 | | var nextOccurence = _cronParser.GetNextOccurrence(_cronExpression); |
| | 12 | 66 | | var delay = nextOccurence - now; |
| | | 67 | | |
| | 12 | 68 | | if (!adjusted && delay <= TimeSpan.Zero) |
| | | 69 | | { |
| | 4 | 70 | | adjusted = true; |
| | 4 | 71 | | continue; |
| | | 72 | | } |
| | | 73 | | |
| | 8 | 74 | | TrySetupTimer(delay); |
| | | 75 | | break; |
| | | 76 | | } |
| | 8 | 77 | | } |
| | | 78 | | |
| | | 79 | | private void TrySetupTimer(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 | | { |
| | 2 | 85 | | _logger.LogWarning("Calculated delay is {Delay} which is not positive. Using minimum delay of 1ms to ensure |
| | 2 | 86 | | delay = TimeSpan.FromMilliseconds(1); |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | try |
| | | 90 | | { |
| | 8 | 91 | | SetupTimer(delay); |
| | 8 | 92 | | } |
| | 0 | 93 | | catch (ArgumentException e) |
| | | 94 | | { |
| | 0 | 95 | | _logger.LogError(e, "Failed to setup timer for scheduled task"); |
| | 0 | 96 | | } |
| | 8 | 97 | | } |
| | | 98 | | |
| | | 99 | | private void SetupTimer(TimeSpan delay) |
| | | 100 | | { |
| | 8 | 101 | | _timer = new(delay.TotalMilliseconds) |
| | 8 | 102 | | { |
| | 8 | 103 | | Enabled = true |
| | 8 | 104 | | }; |
| | | 105 | | |
| | 8 | 106 | | _timer.Elapsed += async (_, _) => |
| | 8 | 107 | | { |
| | 1 | 108 | | _timer?.Dispose(); |
| | 1 | 109 | | _timer = null; |
| | 8 | 110 | | |
| | 8 | 111 | | // Early exit if disposed to prevent accessing disposed resources |
| | 1 | 112 | | if (_disposed) |
| | 0 | 113 | | return; |
| | 8 | 114 | | |
| | 1 | 115 | | IServiceScope? scope = null; |
| | 8 | 116 | | try |
| | 8 | 117 | | { |
| | 1 | 118 | | scope = _scopeFactory.CreateScope(); |
| | 1 | 119 | | } |
| | 0 | 120 | | catch (ObjectDisposedException) |
| | 8 | 121 | | { |
| | 8 | 122 | | // Service provider was disposed, exit gracefully |
| | 0 | 123 | | return; |
| | 8 | 124 | | } |
| | 8 | 125 | | |
| | 1 | 126 | | using (scope) |
| | 8 | 127 | | { |
| | 1 | 128 | | var commandSender = scope.ServiceProvider.GetRequiredService<ICommandSender>(); |
| | 1 | 129 | | var cancellationToken = _cancellationTokenSource.Token; |
| | 8 | 130 | | |
| | 1 | 131 | | if (!cancellationToken.IsCancellationRequested) |
| | 8 | 132 | | { |
| | 1 | 133 | | var acquired = false; |
| | 8 | 134 | | try |
| | 8 | 135 | | { |
| | 1 | 136 | | acquired = await _executionSemaphore.WaitAsync(0, cancellationToken); |
| | 1 | 137 | | if (!acquired) return; |
| | 8 | 138 | | |
| | 1 | 139 | | _executing = true; |
| | 1 | 140 | | await commandSender.SendAsync(new RunScheduledTask(_task), cancellationToken); |
| | 8 | 141 | | |
| | 1 | 142 | | if (_cancellationRequested) |
| | 8 | 143 | | { |
| | 1 | 144 | | _cancellationRequested = false; |
| | 1 | 145 | | _cancellationTokenSource.Cancel(); |
| | 8 | 146 | | } |
| | 1 | 147 | | } |
| | 0 | 148 | | catch (ObjectDisposedException) |
| | 8 | 149 | | { |
| | 8 | 150 | | // Semaphore was disposed during execution, exit gracefully |
| | 0 | 151 | | return; |
| | 8 | 152 | | } |
| | 0 | 153 | | catch (Exception e) |
| | 8 | 154 | | { |
| | 8 | 155 | | // Only log if not disposed to avoid logging after test context is disposed |
| | 0 | 156 | | if (!_disposed) |
| | 8 | 157 | | { |
| | 8 | 158 | | try |
| | 8 | 159 | | { |
| | 0 | 160 | | _logger.LogError(e, "Error executing scheduled task"); |
| | 0 | 161 | | } |
| | 0 | 162 | | catch |
| | 8 | 163 | | { |
| | 8 | 164 | | // Ignore logging errors (e.g., when test output is no longer available) |
| | 0 | 165 | | } |
| | 8 | 166 | | } |
| | 0 | 167 | | } |
| | 8 | 168 | | finally |
| | 8 | 169 | | { |
| | 1 | 170 | | _executing = false; |
| | 1 | 171 | | if (acquired) |
| | 8 | 172 | | { |
| | 8 | 173 | | try |
| | 8 | 174 | | { |
| | 1 | 175 | | _executionSemaphore.Release(); |
| | 1 | 176 | | } |
| | 0 | 177 | | catch (ObjectDisposedException) |
| | 8 | 178 | | { |
| | 8 | 179 | | // Semaphore was disposed, ignore |
| | 0 | 180 | | } |
| | 8 | 181 | | } |
| | 8 | 182 | | } |
| | 8 | 183 | | } |
| | 8 | 184 | | |
| | 8 | 185 | | // Check again if disposed before scheduling next execution |
| | 1 | 186 | | if (!cancellationToken.IsCancellationRequested && !_disposed) |
| | 0 | 187 | | Schedule(); |
| | 1 | 188 | | } |
| | 9 | 189 | | }; |
| | 8 | 190 | | } |
| | | 191 | | |
| | | 192 | | void IDisposable.Dispose() |
| | | 193 | | { |
| | 8 | 194 | | if (_disposed) |
| | 2 | 195 | | return; |
| | | 196 | | |
| | 6 | 197 | | _disposed = true; |
| | 6 | 198 | | _timer?.Dispose(); |
| | 6 | 199 | | _cancellationTokenSource.Dispose(); |
| | 6 | 200 | | _executionSemaphore.Dispose(); |
| | 6 | 201 | | } |
| | | 202 | | } |