-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathScheduledSpecificInstantTask.cs
More file actions
150 lines (132 loc) · 4.8 KB
/
Copy pathScheduledSpecificInstantTask.cs
File metadata and controls
150 lines (132 loc) · 4.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using Elsa.Common;
using Elsa.Mediator.Contracts;
using Elsa.Scheduling.Commands;
using Elsa.Scheduling.Options;
using Elsa.Scheduling.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Timer = System.Timers.Timer;
using OptionsFactory = Microsoft.Extensions.Options.Options;
namespace Elsa.Scheduling.ScheduledTasks;
/// <summary>
/// A task that is scheduled to execute at a specific instant.
/// </summary>
public class ScheduledSpecificInstantTask : IScheduledTask, IDisposable
{
private static readonly PastDueScheduleStaggerer DefaultPastDueScheduleStaggerer = new(OptionsFactory.Create(new SchedulingOptions()));
private readonly ITask _task;
private readonly ISystemClock _systemClock;
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<ScheduledSpecificInstantTask> _logger;
private readonly PastDueScheduleStaggerer _pastDueScheduleStaggerer;
private readonly DateTimeOffset _startAt;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly SemaphoreSlim _executionSemaphore = new(1, 1);
private Timer? _timer;
private bool _executing;
private bool _cancellationRequested;
private bool _disposed;
/// <summary>
/// Initializes a new instance of <see cref="ScheduledSpecificInstantTask"/>.
/// </summary>
public ScheduledSpecificInstantTask(
ITask task,
DateTimeOffset startAt,
ISystemClock systemClock,
IServiceScopeFactory scopeFactory,
ILogger<ScheduledSpecificInstantTask> logger)
: this(task, startAt, systemClock, scopeFactory, logger, DefaultPastDueScheduleStaggerer)
{
}
/// <summary>
/// Initializes a new instance of <see cref="ScheduledSpecificInstantTask"/>.
/// </summary>
[ActivatorUtilitiesConstructor]
public ScheduledSpecificInstantTask(
ITask task,
DateTimeOffset startAt,
ISystemClock systemClock,
IServiceScopeFactory scopeFactory,
ILogger<ScheduledSpecificInstantTask> logger,
PastDueScheduleStaggerer pastDueScheduleStaggerer)
{
_task = task;
_systemClock = systemClock;
_scopeFactory = scopeFactory;
_logger = logger;
_pastDueScheduleStaggerer = pastDueScheduleStaggerer;
_startAt = startAt;
_cancellationTokenSource = new();
Schedule();
}
/// <inheritdoc />
public void Cancel()
{
_timer?.Dispose();
if (_executing)
{
_cancellationRequested = true;
return;
}
_cancellationTokenSource.Cancel();
}
private void Schedule()
{
var now = _systemClock.UtcNow;
var delay = _startAt - now;
var adjustedDelay = _pastDueScheduleStaggerer.GetDelay(delay);
if (delay <= TimeSpan.Zero)
{
_logger.LogDebug("Calculated delay is {Delay} which is not positive. Using catch-up delay of {CatchUpDelay}", delay, adjustedDelay);
}
_timer = new(adjustedDelay.TotalMilliseconds)
{
Enabled = true
};
_timer.Elapsed += async (_, _) =>
{
_timer?.Dispose();
_timer = null;
// Check if disposed before proceeding
if (_disposed) return;
using var scope = _scopeFactory.CreateScope();
var commandSender = scope.ServiceProvider.GetRequiredService<ICommandSender>();
// Check disposed again before accessing CancellationTokenSource
if (_disposed) return;
var cancellationToken = _cancellationTokenSource.Token;
if (!cancellationToken.IsCancellationRequested)
{
var acquired = false;
try
{
acquired = await _executionSemaphore.WaitAsync(0, cancellationToken);
if (!acquired) return;
_executing = true;
await commandSender.SendAsync(new RunScheduledTask(_task), cancellationToken);
if (_cancellationRequested)
{
_cancellationRequested = false;
_cancellationTokenSource.Cancel();
}
}
catch (Exception e)
{
_logger.LogError(e, "Error executing scheduled task");
}
finally
{
_executing = false;
if (acquired && !_disposed)
_executionSemaphore.Release();
}
}
};
}
void IDisposable.Dispose()
{
_disposed = true;
_timer?.Dispose();
_cancellationTokenSource.Dispose();
_executionSemaphore.Dispose();
}
}