| | | 1 | | #nullable disable |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Linq; |
| | | 8 | | using System.Text.Json; |
| | | 9 | | using System.Threading; |
| | | 10 | | using System.Threading.Tasks; |
| | | 11 | | using Emby.Server.Implementations.ScheduledTasks.Triggers; |
| | | 12 | | using Jellyfin.Data.Events; |
| | | 13 | | using Jellyfin.Extensions.Json; |
| | | 14 | | using MediaBrowser.Common.Configuration; |
| | | 15 | | using MediaBrowser.Common.Extensions; |
| | | 16 | | using MediaBrowser.Model.Tasks; |
| | | 17 | | using Microsoft.Extensions.Logging; |
| | | 18 | | |
| | | 19 | | namespace Emby.Server.Implementations.ScheduledTasks; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Class ScheduledTaskWorker. |
| | | 23 | | /// </summary> |
| | | 24 | | public class ScheduledTaskWorker : IScheduledTaskWorker |
| | | 25 | | { |
| | 420 | 26 | | private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; |
| | | 27 | | private readonly IApplicationPaths _applicationPaths; |
| | | 28 | | private readonly ILogger _logger; |
| | | 29 | | private readonly ITaskManager _taskManager; |
| | 420 | 30 | | private readonly Lock _lastExecutionResultSyncLock = new(); |
| | | 31 | | private bool _readFromFile; |
| | | 32 | | private TaskResult _lastExecutionResult; |
| | | 33 | | private Task _currentTask; |
| | | 34 | | private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers; |
| | | 35 | | private string _id; |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <param name="scheduledTask">The scheduled task.</param> |
| | | 41 | | /// <param name="applicationPaths">The application paths.</param> |
| | | 42 | | /// <param name="taskManager">The task manager.</param> |
| | | 43 | | /// <param name="logger">The logger.</param> |
| | | 44 | | /// <exception cref="ArgumentNullException"> |
| | | 45 | | /// scheduledTask |
| | | 46 | | /// or |
| | | 47 | | /// applicationPaths |
| | | 48 | | /// or |
| | | 49 | | /// taskManager |
| | | 50 | | /// or |
| | | 51 | | /// jsonSerializer |
| | | 52 | | /// or |
| | | 53 | | /// logger. |
| | | 54 | | /// </exception> |
| | | 55 | | public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManage |
| | | 56 | | { |
| | 420 | 57 | | ArgumentNullException.ThrowIfNull(scheduledTask); |
| | 420 | 58 | | ArgumentNullException.ThrowIfNull(applicationPaths); |
| | 420 | 59 | | ArgumentNullException.ThrowIfNull(taskManager); |
| | 420 | 60 | | ArgumentNullException.ThrowIfNull(logger); |
| | | 61 | | |
| | 420 | 62 | | ScheduledTask = scheduledTask; |
| | 420 | 63 | | _applicationPaths = applicationPaths; |
| | 420 | 64 | | _taskManager = taskManager; |
| | 420 | 65 | | _logger = logger; |
| | | 66 | | |
| | 420 | 67 | | InitTriggerEvents(); |
| | 420 | 68 | | } |
| | | 69 | | |
| | | 70 | | /// <inheritdoc /> |
| | | 71 | | public event EventHandler<GenericEventArgs<double>> TaskProgress; |
| | | 72 | | |
| | | 73 | | /// <inheritdoc /> |
| | | 74 | | public IScheduledTask ScheduledTask { get; private set; } |
| | | 75 | | |
| | | 76 | | /// <inheritdoc /> |
| | | 77 | | public TaskResult LastExecutionResult |
| | | 78 | | { |
| | | 79 | | get |
| | | 80 | | { |
| | 384 | 81 | | var path = GetHistoryFilePath(); |
| | | 82 | | |
| | | 83 | | lock (_lastExecutionResultSyncLock) |
| | | 84 | | { |
| | 384 | 85 | | if (_lastExecutionResult is null && !_readFromFile) |
| | | 86 | | { |
| | 336 | 87 | | if (File.Exists(path)) |
| | | 88 | | { |
| | 0 | 89 | | var bytes = File.ReadAllBytes(path); |
| | 0 | 90 | | if (bytes.Length > 0) |
| | | 91 | | { |
| | | 92 | | try |
| | | 93 | | { |
| | 0 | 94 | | _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions); |
| | 0 | 95 | | } |
| | 0 | 96 | | catch (JsonException ex) |
| | | 97 | | { |
| | 0 | 98 | | _logger.LogError(ex, "Error deserializing {File}", path); |
| | 0 | 99 | | } |
| | | 100 | | } |
| | | 101 | | else |
| | | 102 | | { |
| | 0 | 103 | | _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", p |
| | | 104 | | } |
| | | 105 | | } |
| | | 106 | | |
| | 336 | 107 | | _readFromFile = true; |
| | | 108 | | } |
| | 384 | 109 | | } |
| | | 110 | | |
| | 384 | 111 | | return _lastExecutionResult; |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | private set |
| | | 115 | | { |
| | 31 | 116 | | _lastExecutionResult = value; |
| | | 117 | | |
| | 31 | 118 | | var path = GetHistoryFilePath(); |
| | 31 | 119 | | Directory.CreateDirectory(Path.GetDirectoryName(path)); |
| | | 120 | | |
| | | 121 | | lock (_lastExecutionResultSyncLock) |
| | | 122 | | { |
| | 31 | 123 | | using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); |
| | 31 | 124 | | using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream); |
| | 31 | 125 | | JsonSerializer.Serialize(jsonStream, value, _jsonOptions); |
| | | 126 | | } |
| | 31 | 127 | | } |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <inheritdoc /> |
| | 498 | 131 | | public string Name => ScheduledTask.Name; |
| | | 132 | | |
| | | 133 | | /// <inheritdoc /> |
| | 0 | 134 | | public string Description => ScheduledTask.Description; |
| | | 135 | | |
| | | 136 | | /// <inheritdoc /> |
| | 0 | 137 | | public string Category => ScheduledTask.Category; |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// Gets or sets the current cancellation token. |
| | | 141 | | /// </summary> |
| | | 142 | | /// <value>The current cancellation token source.</value> |
| | | 143 | | private CancellationTokenSource CurrentCancellationTokenSource { get; set; } |
| | | 144 | | |
| | | 145 | | /// <summary> |
| | | 146 | | /// Gets or sets the current execution start time. |
| | | 147 | | /// </summary> |
| | | 148 | | /// <value>The current execution start time.</value> |
| | | 149 | | private DateTime CurrentExecutionStartTime { get; set; } |
| | | 150 | | |
| | | 151 | | /// <inheritdoc /> |
| | | 152 | | public TaskState State |
| | | 153 | | { |
| | | 154 | | get |
| | | 155 | | { |
| | 466 | 156 | | if (CurrentCancellationTokenSource is not null) |
| | | 157 | | { |
| | 5 | 158 | | return CurrentCancellationTokenSource.IsCancellationRequested |
| | 5 | 159 | | ? TaskState.Cancelling |
| | 5 | 160 | | : TaskState.Running; |
| | | 161 | | } |
| | | 162 | | |
| | 461 | 163 | | return TaskState.Idle; |
| | | 164 | | } |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | /// <inheritdoc /> |
| | | 168 | | public double? CurrentProgress { get; private set; } |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Gets or sets the triggers that define when the task will run. |
| | | 172 | | /// </summary> |
| | | 173 | | /// <value>The triggers.</value> |
| | | 174 | | private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers |
| | | 175 | | { |
| | 840 | 176 | | get => _triggers; |
| | | 177 | | set |
| | | 178 | | { |
| | 0 | 179 | | ArgumentNullException.ThrowIfNull(value); |
| | | 180 | | |
| | | 181 | | // Cleanup current triggers |
| | 0 | 182 | | if (_triggers is not null) |
| | | 183 | | { |
| | 0 | 184 | | DisposeTriggers(); |
| | | 185 | | } |
| | | 186 | | |
| | 0 | 187 | | _triggers = value.ToArray(); |
| | | 188 | | |
| | 0 | 189 | | ReloadTriggerEvents(false); |
| | 0 | 190 | | } |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | /// <inheritdoc /> |
| | | 194 | | public IReadOnlyList<TaskTriggerInfo> Triggers |
| | | 195 | | { |
| | | 196 | | get |
| | | 197 | | { |
| | 0 | 198 | | return Array.ConvertAll(InternalTriggers, i => i.Item1); |
| | | 199 | | } |
| | | 200 | | |
| | | 201 | | set |
| | | 202 | | { |
| | 0 | 203 | | ArgumentNullException.ThrowIfNull(value); |
| | | 204 | | |
| | | 205 | | // This null check is not great, but is needed to handle bad user input, or user mucking with the config fil |
| | 0 | 206 | | var triggerList = value.Where(i => i is not null).ToArray(); |
| | | 207 | | |
| | 0 | 208 | | SaveTriggers(triggerList); |
| | | 209 | | |
| | 0 | 210 | | InternalTriggers = Array.ConvertAll(triggerList, i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger |
| | 0 | 211 | | } |
| | | 212 | | } |
| | | 213 | | |
| | | 214 | | /// <inheritdoc /> |
| | | 215 | | public string Id |
| | | 216 | | { |
| | | 217 | | get |
| | | 218 | | { |
| | 866 | 219 | | return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture); |
| | | 220 | | } |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | private void InitTriggerEvents() |
| | | 224 | | { |
| | 420 | 225 | | _triggers = LoadTriggers(); |
| | 420 | 226 | | ReloadTriggerEvents(true); |
| | 420 | 227 | | } |
| | | 228 | | |
| | | 229 | | /// <inheritdoc /> |
| | | 230 | | public void ReloadTriggerEvents() |
| | | 231 | | { |
| | 0 | 232 | | ReloadTriggerEvents(false); |
| | 0 | 233 | | } |
| | | 234 | | |
| | | 235 | | /// <summary> |
| | | 236 | | /// Reloads the trigger events. |
| | | 237 | | /// </summary> |
| | | 238 | | /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param> |
| | | 239 | | private void ReloadTriggerEvents(bool isApplicationStartup) |
| | | 240 | | { |
| | 1596 | 241 | | foreach (var triggerInfo in InternalTriggers) |
| | | 242 | | { |
| | 378 | 243 | | var trigger = triggerInfo.Item2; |
| | | 244 | | |
| | 378 | 245 | | trigger.Stop(); |
| | | 246 | | |
| | 378 | 247 | | trigger.Triggered -= OnTriggerTriggered; |
| | 378 | 248 | | trigger.Triggered += OnTriggerTriggered; |
| | 378 | 249 | | trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup); |
| | | 250 | | } |
| | 420 | 251 | | } |
| | | 252 | | |
| | | 253 | | /// <summary> |
| | | 254 | | /// Handles the Triggered event of the trigger control. |
| | | 255 | | /// </summary> |
| | | 256 | | /// <param name="sender">The source of the event.</param> |
| | | 257 | | /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> |
| | | 258 | | private async void OnTriggerTriggered(object sender, EventArgs e) |
| | | 259 | | { |
| | | 260 | | var trigger = (ITaskTrigger)sender; |
| | | 261 | | |
| | | 262 | | if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled) |
| | | 263 | | { |
| | | 264 | | return; |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | _logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name); |
| | | 268 | | |
| | | 269 | | trigger.Stop(); |
| | | 270 | | |
| | | 271 | | _taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions); |
| | | 272 | | |
| | | 273 | | await Task.Delay(1000).ConfigureAwait(false); |
| | | 274 | | |
| | | 275 | | trigger.Start(LastExecutionResult, _logger, Name, false); |
| | | 276 | | } |
| | | 277 | | |
| | | 278 | | /// <summary> |
| | | 279 | | /// Executes the task. |
| | | 280 | | /// </summary> |
| | | 281 | | /// <param name="options">Task options.</param> |
| | | 282 | | /// <returns>Task.</returns> |
| | | 283 | | /// <exception cref="InvalidOperationException">Cannot execute a Task that is already running.</exception> |
| | | 284 | | public async Task Execute(TaskOptions options) |
| | | 285 | | { |
| | | 286 | | var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false)); |
| | | 287 | | |
| | | 288 | | _currentTask = task; |
| | | 289 | | |
| | | 290 | | try |
| | | 291 | | { |
| | | 292 | | await task.ConfigureAwait(false); |
| | | 293 | | } |
| | | 294 | | finally |
| | | 295 | | { |
| | | 296 | | _currentTask = null; |
| | | 297 | | GC.Collect(); |
| | | 298 | | } |
| | | 299 | | } |
| | | 300 | | |
| | | 301 | | private async Task ExecuteInternal(TaskOptions options) |
| | | 302 | | { |
| | | 303 | | // Cancel the current execution, if any |
| | | 304 | | if (CurrentCancellationTokenSource is not null) |
| | | 305 | | { |
| | | 306 | | throw new InvalidOperationException("Cannot execute a Task that is already running"); |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | var progress = new Progress<double>(); |
| | | 310 | | |
| | | 311 | | CurrentCancellationTokenSource = new CancellationTokenSource(); |
| | | 312 | | |
| | | 313 | | _logger.LogDebug("Executing {0}", Name); |
| | | 314 | | |
| | | 315 | | ((TaskManager)_taskManager).OnTaskExecuting(this); |
| | | 316 | | |
| | | 317 | | progress.ProgressChanged += OnProgressChanged; |
| | | 318 | | |
| | | 319 | | TaskCompletionStatus status; |
| | | 320 | | CurrentExecutionStartTime = DateTime.UtcNow; |
| | | 321 | | |
| | | 322 | | Exception failureException = null; |
| | | 323 | | |
| | | 324 | | try |
| | | 325 | | { |
| | | 326 | | if (options is not null && options.MaxRuntimeTicks.HasValue) |
| | | 327 | | { |
| | | 328 | | CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value)); |
| | | 329 | | } |
| | | 330 | | |
| | | 331 | | await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false); |
| | | 332 | | |
| | | 333 | | status = TaskCompletionStatus.Completed; |
| | | 334 | | } |
| | | 335 | | catch (OperationCanceledException) |
| | | 336 | | { |
| | | 337 | | status = TaskCompletionStatus.Cancelled; |
| | | 338 | | } |
| | | 339 | | catch (Exception ex) |
| | | 340 | | { |
| | | 341 | | _logger.LogError(ex, "Error executing Scheduled Task"); |
| | | 342 | | |
| | | 343 | | failureException = ex; |
| | | 344 | | |
| | | 345 | | status = TaskCompletionStatus.Failed; |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | var startTime = CurrentExecutionStartTime; |
| | | 349 | | var endTime = DateTime.UtcNow; |
| | | 350 | | |
| | | 351 | | progress.ProgressChanged -= OnProgressChanged; |
| | | 352 | | CurrentCancellationTokenSource.Dispose(); |
| | | 353 | | CurrentCancellationTokenSource = null; |
| | | 354 | | CurrentProgress = null; |
| | | 355 | | |
| | | 356 | | OnTaskCompleted(startTime, endTime, status, failureException); |
| | | 357 | | } |
| | | 358 | | |
| | | 359 | | /// <summary> |
| | | 360 | | /// Progress_s the progress changed. |
| | | 361 | | /// </summary> |
| | | 362 | | /// <param name="sender">The sender.</param> |
| | | 363 | | /// <param name="e">The e.</param> |
| | | 364 | | private void OnProgressChanged(object sender, double e) |
| | | 365 | | { |
| | 271 | 366 | | e = Math.Min(e, 100); |
| | | 367 | | |
| | 271 | 368 | | CurrentProgress = e; |
| | | 369 | | |
| | 271 | 370 | | TaskProgress?.Invoke(this, new GenericEventArgs<double>(e)); |
| | 270 | 371 | | } |
| | | 372 | | |
| | | 373 | | /// <summary> |
| | | 374 | | /// Stops the task if it is currently executing. |
| | | 375 | | /// </summary> |
| | | 376 | | /// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception> |
| | | 377 | | public void Cancel() |
| | | 378 | | { |
| | 0 | 379 | | if (State != TaskState.Running) |
| | | 380 | | { |
| | 0 | 381 | | throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state."); |
| | | 382 | | } |
| | | 383 | | |
| | 0 | 384 | | CancelIfRunning(); |
| | 0 | 385 | | } |
| | | 386 | | |
| | | 387 | | /// <summary> |
| | | 388 | | /// Cancels if running. |
| | | 389 | | /// </summary> |
| | | 390 | | public void CancelIfRunning() |
| | | 391 | | { |
| | 20 | 392 | | if (State == TaskState.Running) |
| | | 393 | | { |
| | 0 | 394 | | _logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name); |
| | 0 | 395 | | CurrentCancellationTokenSource.Cancel(); |
| | | 396 | | } |
| | 20 | 397 | | } |
| | | 398 | | |
| | | 399 | | /// <summary> |
| | | 400 | | /// Gets the scheduled tasks configuration directory. |
| | | 401 | | /// </summary> |
| | | 402 | | /// <returns>System.String.</returns> |
| | | 403 | | private string GetScheduledTasksConfigurationDirectory() |
| | | 404 | | { |
| | 420 | 405 | | return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks"); |
| | | 406 | | } |
| | | 407 | | |
| | | 408 | | /// <summary> |
| | | 409 | | /// Gets the scheduled tasks data directory. |
| | | 410 | | /// </summary> |
| | | 411 | | /// <returns>System.String.</returns> |
| | | 412 | | private string GetScheduledTasksDataDirectory() |
| | | 413 | | { |
| | 415 | 414 | | return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks"); |
| | | 415 | | } |
| | | 416 | | |
| | | 417 | | /// <summary> |
| | | 418 | | /// Gets the history file path. |
| | | 419 | | /// </summary> |
| | | 420 | | /// <value>The history file path.</value> |
| | | 421 | | private string GetHistoryFilePath() |
| | | 422 | | { |
| | 415 | 423 | | return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js"); |
| | | 424 | | } |
| | | 425 | | |
| | | 426 | | /// <summary> |
| | | 427 | | /// Gets the configuration file path. |
| | | 428 | | /// </summary> |
| | | 429 | | /// <returns>System.String.</returns> |
| | | 430 | | private string GetConfigurationFilePath() |
| | | 431 | | { |
| | 420 | 432 | | return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js"); |
| | | 433 | | } |
| | | 434 | | |
| | | 435 | | /// <summary> |
| | | 436 | | /// Loads the triggers. |
| | | 437 | | /// </summary> |
| | | 438 | | /// <returns>IEnumerable{BaseTaskTrigger}.</returns> |
| | | 439 | | private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers() |
| | | 440 | | { |
| | | 441 | | // This null check is not great, but is needed to handle bad user input, or user mucking with the config file in |
| | 420 | 442 | | var settings = LoadTriggerSettings().Where(i => i is not null); |
| | | 443 | | |
| | 420 | 444 | | return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray(); |
| | | 445 | | } |
| | | 446 | | |
| | | 447 | | private TaskTriggerInfo[] LoadTriggerSettings() |
| | | 448 | | { |
| | 420 | 449 | | string path = GetConfigurationFilePath(); |
| | 420 | 450 | | TaskTriggerInfo[] list = null; |
| | 420 | 451 | | if (File.Exists(path)) |
| | | 452 | | { |
| | 0 | 453 | | var bytes = File.ReadAllBytes(path); |
| | 0 | 454 | | list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions); |
| | | 455 | | } |
| | | 456 | | |
| | | 457 | | // Return defaults if file doesn't exist. |
| | 420 | 458 | | return list ?? GetDefaultTriggers(); |
| | | 459 | | } |
| | | 460 | | |
| | | 461 | | private TaskTriggerInfo[] GetDefaultTriggers() |
| | | 462 | | { |
| | | 463 | | try |
| | | 464 | | { |
| | 420 | 465 | | return ScheduledTask.GetDefaultTriggers().ToArray(); |
| | | 466 | | } |
| | 0 | 467 | | catch |
| | | 468 | | { |
| | 0 | 469 | | return |
| | 0 | 470 | | [ |
| | 0 | 471 | | new() |
| | 0 | 472 | | { |
| | 0 | 473 | | IntervalTicks = TimeSpan.FromDays(1).Ticks, |
| | 0 | 474 | | Type = TaskTriggerInfoType.IntervalTrigger |
| | 0 | 475 | | } |
| | 0 | 476 | | ]; |
| | | 477 | | } |
| | 420 | 478 | | } |
| | | 479 | | |
| | | 480 | | /// <summary> |
| | | 481 | | /// Saves the triggers. |
| | | 482 | | /// </summary> |
| | | 483 | | /// <param name="triggers">The triggers.</param> |
| | | 484 | | private void SaveTriggers(TaskTriggerInfo[] triggers) |
| | | 485 | | { |
| | 0 | 486 | | var path = GetConfigurationFilePath(); |
| | | 487 | | |
| | 0 | 488 | | Directory.CreateDirectory(Path.GetDirectoryName(path)); |
| | 0 | 489 | | using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); |
| | 0 | 490 | | using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream); |
| | 0 | 491 | | JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions); |
| | 0 | 492 | | } |
| | | 493 | | |
| | | 494 | | /// <summary> |
| | | 495 | | /// Called when [task completed]. |
| | | 496 | | /// </summary> |
| | | 497 | | /// <param name="startTime">The start time.</param> |
| | | 498 | | /// <param name="endTime">The end time.</param> |
| | | 499 | | /// <param name="status">The status.</param> |
| | | 500 | | /// <param name="ex">The exception.</param> |
| | | 501 | | private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex) |
| | | 502 | | { |
| | 31 | 503 | | var elapsedTime = endTime - startTime; |
| | | 504 | | |
| | 31 | 505 | | _logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.To |
| | | 506 | | |
| | 31 | 507 | | var result = new TaskResult |
| | 31 | 508 | | { |
| | 31 | 509 | | StartTimeUtc = startTime, |
| | 31 | 510 | | EndTimeUtc = endTime, |
| | 31 | 511 | | Status = status, |
| | 31 | 512 | | Name = Name, |
| | 31 | 513 | | Id = Id |
| | 31 | 514 | | }; |
| | | 515 | | |
| | 31 | 516 | | result.Key = ScheduledTask.Key; |
| | | 517 | | |
| | 31 | 518 | | if (ex is not null) |
| | | 519 | | { |
| | 0 | 520 | | result.ErrorMessage = ex.Message; |
| | 0 | 521 | | result.LongErrorMessage = ex.StackTrace; |
| | | 522 | | } |
| | | 523 | | |
| | 31 | 524 | | LastExecutionResult = result; |
| | | 525 | | |
| | 31 | 526 | | ((TaskManager)_taskManager).OnTaskCompleted(this, result); |
| | 31 | 527 | | } |
| | | 528 | | |
| | | 529 | | /// <inheritdoc /> |
| | | 530 | | public void Dispose() |
| | | 531 | | { |
| | 420 | 532 | | Dispose(true); |
| | 420 | 533 | | GC.SuppressFinalize(this); |
| | 420 | 534 | | } |
| | | 535 | | |
| | | 536 | | /// <summary> |
| | | 537 | | /// Releases unmanaged and - optionally - managed resources. |
| | | 538 | | /// </summary> |
| | | 539 | | /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only |
| | | 540 | | protected virtual void Dispose(bool dispose) |
| | | 541 | | { |
| | 420 | 542 | | if (dispose) |
| | | 543 | | { |
| | 420 | 544 | | DisposeTriggers(); |
| | | 545 | | |
| | 420 | 546 | | var wasRunning = State == TaskState.Running; |
| | 420 | 547 | | var startTime = CurrentExecutionStartTime; |
| | | 548 | | |
| | 420 | 549 | | var token = CurrentCancellationTokenSource; |
| | 420 | 550 | | if (token is not null) |
| | | 551 | | { |
| | | 552 | | try |
| | | 553 | | { |
| | 5 | 554 | | _logger.LogInformation("{Name}: Cancelling", Name); |
| | 5 | 555 | | token.Cancel(); |
| | 5 | 556 | | } |
| | 0 | 557 | | catch (Exception ex) |
| | | 558 | | { |
| | 0 | 559 | | _logger.LogError(ex, "Error calling CancellationToken.Cancel();"); |
| | 0 | 560 | | } |
| | | 561 | | } |
| | | 562 | | |
| | 420 | 563 | | var task = _currentTask; |
| | 420 | 564 | | if (task is not null) |
| | | 565 | | { |
| | | 566 | | try |
| | | 567 | | { |
| | 5 | 568 | | _logger.LogInformation("{Name}: Waiting on Task", Name); |
| | 5 | 569 | | var exited = task.Wait(2000); |
| | | 570 | | |
| | 5 | 571 | | if (exited) |
| | | 572 | | { |
| | 5 | 573 | | _logger.LogInformation("{Name}: Task exited", Name); |
| | | 574 | | } |
| | | 575 | | else |
| | | 576 | | { |
| | 0 | 577 | | _logger.LogInformation("{Name}: Timed out waiting for task to stop", Name); |
| | | 578 | | } |
| | 5 | 579 | | } |
| | 0 | 580 | | catch (Exception ex) |
| | | 581 | | { |
| | 0 | 582 | | _logger.LogError(ex, "Error calling Task.WaitAll();"); |
| | 0 | 583 | | } |
| | | 584 | | } |
| | | 585 | | |
| | 420 | 586 | | if (token is not null) |
| | | 587 | | { |
| | | 588 | | try |
| | | 589 | | { |
| | 5 | 590 | | _logger.LogDebug("{Name}: Disposing CancellationToken", Name); |
| | 5 | 591 | | token.Dispose(); |
| | 5 | 592 | | } |
| | 0 | 593 | | catch (Exception ex) |
| | | 594 | | { |
| | 0 | 595 | | _logger.LogError(ex, "Error calling CancellationToken.Dispose();"); |
| | 0 | 596 | | } |
| | | 597 | | } |
| | | 598 | | |
| | 420 | 599 | | if (wasRunning) |
| | | 600 | | { |
| | 5 | 601 | | OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null); |
| | | 602 | | } |
| | | 603 | | } |
| | 420 | 604 | | } |
| | | 605 | | |
| | | 606 | | /// <summary> |
| | | 607 | | /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger. |
| | | 608 | | /// </summary> |
| | | 609 | | /// <param name="info">The info.</param> |
| | | 610 | | /// <returns>BaseTaskTrigger.</returns> |
| | | 611 | | /// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception> |
| | | 612 | | private ITaskTrigger GetTrigger(TaskTriggerInfo info) |
| | | 613 | | { |
| | 378 | 614 | | var options = new TaskOptions |
| | 378 | 615 | | { |
| | 378 | 616 | | MaxRuntimeTicks = info.MaxRuntimeTicks |
| | 378 | 617 | | }; |
| | | 618 | | |
| | 378 | 619 | | if (info.Type == TaskTriggerInfoType.DailyTrigger) |
| | | 620 | | { |
| | 42 | 621 | | if (!info.TimeOfDayTicks.HasValue) |
| | | 622 | | { |
| | 0 | 623 | | throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info)); |
| | | 624 | | } |
| | | 625 | | |
| | 42 | 626 | | return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options); |
| | | 627 | | } |
| | | 628 | | |
| | 336 | 629 | | if (info.Type == TaskTriggerInfoType.WeeklyTrigger) |
| | | 630 | | { |
| | 0 | 631 | | if (!info.TimeOfDayTicks.HasValue) |
| | | 632 | | { |
| | 0 | 633 | | throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info)); |
| | | 634 | | } |
| | | 635 | | |
| | 0 | 636 | | if (!info.DayOfWeek.HasValue) |
| | | 637 | | { |
| | 0 | 638 | | throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info)); |
| | | 639 | | } |
| | | 640 | | |
| | 0 | 641 | | return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options); |
| | | 642 | | } |
| | | 643 | | |
| | 336 | 644 | | if (info.Type == TaskTriggerInfoType.IntervalTrigger) |
| | | 645 | | { |
| | 273 | 646 | | if (!info.IntervalTicks.HasValue) |
| | | 647 | | { |
| | 0 | 648 | | throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info)); |
| | | 649 | | } |
| | | 650 | | |
| | 273 | 651 | | return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options); |
| | | 652 | | } |
| | | 653 | | |
| | 63 | 654 | | if (info.Type == TaskTriggerInfoType.StartupTrigger) |
| | | 655 | | { |
| | 63 | 656 | | return new StartupTrigger(options); |
| | | 657 | | } |
| | | 658 | | |
| | 0 | 659 | | throw new ArgumentException("Unrecognized trigger type: " + info.Type); |
| | | 660 | | } |
| | | 661 | | |
| | | 662 | | /// <summary> |
| | | 663 | | /// Disposes each trigger. |
| | | 664 | | /// </summary> |
| | | 665 | | private void DisposeTriggers() |
| | | 666 | | { |
| | 1596 | 667 | | foreach (var triggerInfo in InternalTriggers) |
| | | 668 | | { |
| | 378 | 669 | | var trigger = triggerInfo.Item2; |
| | 378 | 670 | | trigger.Triggered -= OnTriggerTriggered; |
| | 378 | 671 | | trigger.Stop(); |
| | 378 | 672 | | if (trigger is IDisposable disposable) |
| | | 673 | | { |
| | 315 | 674 | | disposable.Dispose(); |
| | | 675 | | } |
| | | 676 | | } |
| | 420 | 677 | | } |
| | | 678 | | } |