Files
jellyfin-jellyfin-1/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs

679 lines
20 KiB
C#
Raw Normal View History

#nullable disable
2019-01-12 21:41:08 +01:00
using System;
2024-09-04 17:38:10 +02:00
using System.Collections.Generic;
using System.Globalization;
2016-10-29 01:40:15 -04:00
using System.IO;
using System.Linq;
using System.Text.Json;
2016-10-29 01:40:15 -04:00
using System.Threading;
using System.Threading.Tasks;
2021-12-15 18:25:36 +01:00
using Emby.Server.Implementations.ScheduledTasks.Triggers;
using Jellyfin.Data.Events;
2021-10-02 12:53:51 -04:00
using Jellyfin.Extensions.Json;
2016-10-29 01:40:15 -04:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
namespace Emby.Server.Implementations.ScheduledTasks;
/// <summary>
/// Class ScheduledTaskWorker.
/// </summary>
public class ScheduledTaskWorker : IScheduledTaskWorker
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private readonly IApplicationPaths _applicationPaths;
private readonly ILogger _logger;
private readonly ITaskManager _taskManager;
private readonly Lock _lastExecutionResultSyncLock = new();
private bool _readFromFile;
private TaskResult _lastExecutionResult;
private Task _currentTask;
private Tuple<TaskTriggerInfo, ITaskTrigger>[] _triggers;
private string _id;
2016-10-29 01:40:15 -04:00
/// <summary>
2025-04-30 09:29:13 +02:00
/// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class.
2016-10-29 01:40:15 -04:00
/// </summary>
2025-04-30 09:29:13 +02:00
/// <param name="scheduledTask">The scheduled task.</param>
/// <param name="applicationPaths">The application paths.</param>
/// <param name="taskManager">The task manager.</param>
/// <param name="logger">The logger.</param>
/// <exception cref="ArgumentNullException">
/// scheduledTask
/// or
/// applicationPaths
/// or
/// taskManager
/// or
/// jsonSerializer
/// or
/// logger.
/// </exception>
public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
ArgumentNullException.ThrowIfNull(scheduledTask);
ArgumentNullException.ThrowIfNull(applicationPaths);
ArgumentNullException.ThrowIfNull(taskManager);
ArgumentNullException.ThrowIfNull(logger);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
ScheduledTask = scheduledTask;
_applicationPaths = applicationPaths;
_taskManager = taskManager;
_logger = logger;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
InitTriggerEvents();
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public event EventHandler<GenericEventArgs<double>> TaskProgress;
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public IScheduledTask ScheduledTask { get; private set; }
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public TaskResult LastExecutionResult
{
get
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
var path = GetHistoryFilePath();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
lock (_lastExecutionResultSyncLock)
{
if (_lastExecutionResult is null && !_readFromFile)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
if (File.Exists(path))
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
var bytes = File.ReadAllBytes(path);
if (bytes.Length > 0)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
try
{
2025-04-30 09:29:13 +02:00
_lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(bytes, _jsonOptions);
}
2025-04-30 09:29:13 +02:00
catch (JsonException ex)
{
2025-04-30 09:29:13 +02:00
_logger.LogError(ex, "Error deserializing {File}", path);
}
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
else
{
_logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path);
}
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
_readFromFile = true;
}
2016-10-29 01:40:15 -04:00
}
2020-06-16 09:43:52 +12:00
2025-04-30 09:29:13 +02:00
return _lastExecutionResult;
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
private set
{
_lastExecutionResult = value;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
var path = GetHistoryFilePath();
Directory.CreateDirectory(Path.GetDirectoryName(path));
lock (_lastExecutionResultSyncLock)
{
using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream);
JsonSerializer.Serialize(jsonStream, value, _jsonOptions);
2016-10-29 01:40:15 -04:00
}
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public string Name => ScheduledTask.Name;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public string Description => ScheduledTask.Description;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public string Category => ScheduledTask.Category;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets or sets the current cancellation token.
/// </summary>
/// <value>The current cancellation token source.</value>
private CancellationTokenSource CurrentCancellationTokenSource { get; set; }
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets or sets the current execution start time.
/// </summary>
/// <value>The current execution start time.</value>
private DateTime CurrentExecutionStartTime { get; set; }
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public TaskState State
{
get
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
if (CurrentCancellationTokenSource is not null)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
return CurrentCancellationTokenSource.IsCancellationRequested
? TaskState.Cancelling
: TaskState.Running;
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
return TaskState.Idle;
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public double? CurrentProgress { get; private set; }
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets or sets the triggers that define when the task will run.
/// </summary>
/// <value>The triggers.</value>
private Tuple<TaskTriggerInfo, ITaskTrigger>[] InternalTriggers
{
get => _triggers;
set
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
ArgumentNullException.ThrowIfNull(value);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
// Cleanup current triggers
if (_triggers is not null)
{
DisposeTriggers();
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
_triggers = value.ToArray();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
ReloadTriggerEvents(false);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public IReadOnlyList<TaskTriggerInfo> Triggers
{
get
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
return Array.ConvertAll(InternalTriggers, i => i.Item1);
}
2020-06-16 09:43:52 +12:00
2025-04-30 09:29:13 +02:00
set
{
ArgumentNullException.ThrowIfNull(value);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
// This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
var triggerList = value.Where(i => i is not null).ToArray();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
SaveTriggers(triggerList);
2016-12-22 10:57:45 -05:00
2025-04-30 09:29:13 +02:00
InternalTriggers = Array.ConvertAll(triggerList, i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i)));
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public string Id
{
get
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
private void InitTriggerEvents()
{
_triggers = LoadTriggers();
ReloadTriggerEvents(true);
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <inheritdoc />
public void ReloadTriggerEvents()
{
ReloadTriggerEvents(false);
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Reloads the trigger events.
/// </summary>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
private void ReloadTriggerEvents(bool isApplicationStartup)
{
foreach (var triggerInfo in InternalTriggers)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
var trigger = triggerInfo.Item2;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
trigger.Stop();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
trigger.Triggered -= OnTriggerTriggered;
trigger.Triggered += OnTriggerTriggered;
trigger.Start(LastExecutionResult, _logger, Name, isApplicationStartup);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Handles the Triggered event of the trigger control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private async void OnTriggerTriggered(object sender, EventArgs e)
{
var trigger = (ITaskTrigger)sender;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled)
{
return;
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
_logger.LogDebug("{0} fired for task: {1}", trigger.GetType().Name, Name);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
trigger.Stop();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
_taskManager.QueueScheduledTask(ScheduledTask, trigger.TaskOptions);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
await Task.Delay(1000).ConfigureAwait(false);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
trigger.Start(LastExecutionResult, _logger, Name, false);
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Executes the task.
/// </summary>
/// <param name="options">Task options.</param>
/// <returns>Task.</returns>
/// <exception cref="InvalidOperationException">Cannot execute a Task that is already running.</exception>
public async Task Execute(TaskOptions options)
{
var task = Task.Run(async () => await ExecuteInternal(options).ConfigureAwait(false));
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
_currentTask = task;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
try
{
await task.ConfigureAwait(false);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
finally
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_currentTask = null;
GC.Collect();
}
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
private async Task ExecuteInternal(TaskOptions options)
{
// Cancel the current execution, if any
if (CurrentCancellationTokenSource is not null)
{
throw new InvalidOperationException("Cannot execute a Task that is already running");
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
var progress = new Progress<double>();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
CurrentCancellationTokenSource = new CancellationTokenSource();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
_logger.LogDebug("Executing {0}", Name);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
((TaskManager)_taskManager).OnTaskExecuting(this);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
progress.ProgressChanged += OnProgressChanged;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
TaskCompletionStatus status;
CurrentExecutionStartTime = DateTime.UtcNow;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
Exception failureException = null;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
try
{
if (options is not null && options.MaxRuntimeTicks.HasValue)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
await ScheduledTask.ExecuteAsync(progress, CurrentCancellationTokenSource.Token).ConfigureAwait(false);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
status = TaskCompletionStatus.Completed;
}
catch (OperationCanceledException)
{
status = TaskCompletionStatus.Cancelled;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error executing Scheduled Task");
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
failureException = ex;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
status = TaskCompletionStatus.Failed;
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
var startTime = CurrentExecutionStartTime;
var endTime = DateTime.UtcNow;
2017-11-03 14:11:04 -04:00
2025-04-30 09:29:13 +02:00
progress.ProgressChanged -= OnProgressChanged;
CurrentCancellationTokenSource.Dispose();
CurrentCancellationTokenSource = null;
CurrentProgress = null;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
OnTaskCompleted(startTime, endTime, status, failureException);
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Progress_s the progress changed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void OnProgressChanged(object sender, double e)
{
e = Math.Min(e, 100);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
CurrentProgress = e;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
TaskProgress?.Invoke(this, new GenericEventArgs<double>(e));
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Stops the task if it is currently executing.
/// </summary>
/// <exception cref="InvalidOperationException">Cannot cancel a Task unless it is in the Running state.</exception>
public void Cancel()
{
if (State != TaskState.Running)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
throw new InvalidOperationException("Cannot cancel a Task unless it is in the Running state.");
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
CancelIfRunning();
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Cancels if running.
/// </summary>
public void CancelIfRunning()
{
if (State == TaskState.Running)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogInformation("Attempting to cancel Scheduled Task {0}", Name);
CurrentCancellationTokenSource.Cancel();
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets the scheduled tasks configuration directory.
/// </summary>
/// <returns>System.String.</returns>
private string GetScheduledTasksConfigurationDirectory()
{
return Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "ScheduledTasks");
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets the scheduled tasks data directory.
/// </summary>
/// <returns>System.String.</returns>
private string GetScheduledTasksDataDirectory()
{
return Path.Combine(_applicationPaths.DataPath, "ScheduledTasks");
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets the history file path.
/// </summary>
/// <value>The history file path.</value>
private string GetHistoryFilePath()
{
return Path.Combine(GetScheduledTasksDataDirectory(), new Guid(Id) + ".js");
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Gets the configuration file path.
/// </summary>
/// <returns>System.String.</returns>
private string GetConfigurationFilePath()
{
return Path.Combine(GetScheduledTasksConfigurationDirectory(), new Guid(Id) + ".js");
}
2018-09-12 19:26:21 +02:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Loads the triggers.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
private Tuple<TaskTriggerInfo, ITaskTrigger>[] LoadTriggers()
{
// This null check is not great, but is needed to handle bad user input, or user mucking with the config file incorrectly
var settings = LoadTriggerSettings().Where(i => i is not null);
return settings.Select(i => new Tuple<TaskTriggerInfo, ITaskTrigger>(i, GetTrigger(i))).ToArray();
}
2018-09-12 19:26:21 +02:00
2025-04-30 09:29:13 +02:00
private TaskTriggerInfo[] LoadTriggerSettings()
{
string path = GetConfigurationFilePath();
TaskTriggerInfo[] list = null;
if (File.Exists(path))
2018-09-12 19:26:21 +02:00
{
2025-04-30 09:29:13 +02:00
var bytes = File.ReadAllBytes(path);
list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(bytes, _jsonOptions);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
// Return defaults if file doesn't exist.
return list ?? GetDefaultTriggers();
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
private TaskTriggerInfo[] GetDefaultTriggers()
{
try
{
return ScheduledTask.GetDefaultTriggers().ToArray();
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
catch
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
return
[
new()
{
IntervalTicks = TimeSpan.FromDays(1).Ticks,
Type = TaskTriggerInfoType.IntervalTrigger
}
];
}
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Saves the triggers.
/// </summary>
/// <param name="triggers">The triggers.</param>
private void SaveTriggers(TaskTriggerInfo[] triggers)
{
var path = GetConfigurationFilePath();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream);
JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions);
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Called when [task completed].
/// </summary>
/// <param name="startTime">The start time.</param>
/// <param name="endTime">The end time.</param>
/// <param name="status">The status.</param>
/// <param name="ex">The exception.</param>
private void OnTaskCompleted(DateTime startTime, DateTime endTime, TaskCompletionStatus status, Exception ex)
{
var elapsedTime = endTime - startTime;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
_logger.LogInformation("{0} {1} after {2} minute(s) and {3} seconds", Name, status, Math.Truncate(elapsedTime.TotalMinutes), elapsedTime.Seconds);
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
var result = new TaskResult
{
StartTimeUtc = startTime,
EndTimeUtc = endTime,
Status = status,
Name = Name,
Id = Id
};
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
result.Key = ScheduledTask.Key;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
if (ex is not null)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
result.ErrorMessage = ex.Message;
result.LongErrorMessage = ex.StackTrace;
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
LastExecutionResult = result;
((TaskManager)_taskManager).OnTaskCompleted(this, result);
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
DisposeTriggers();
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
var wasRunning = State == TaskState.Running;
var startTime = CurrentExecutionStartTime;
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
var token = CurrentCancellationTokenSource;
if (token is not null)
{
try
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogInformation("{Name}: Cancelling", Name);
token.Cancel();
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
catch (Exception ex)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogError(ex, "Error calling CancellationToken.Cancel();");
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
var task = _currentTask;
if (task is not null)
{
try
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogInformation("{Name}: Waiting on Task", Name);
var exited = task.Wait(2000);
if (exited)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogInformation("{Name}: Task exited", Name);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
else
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogInformation("{Name}: Timed out waiting for task to stop", Name);
2016-10-29 01:40:15 -04:00
}
}
2025-04-30 09:29:13 +02:00
catch (Exception ex)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogError(ex, "Error calling Task.WaitAll();");
2016-10-29 01:40:15 -04:00
}
}
2025-04-30 09:29:13 +02:00
if (token is not null)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
try
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
_logger.LogDebug("{Name}: Disposing CancellationToken", Name);
token.Dispose();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calling CancellationToken.Dispose();");
2016-10-29 01:40:15 -04:00
}
}
2025-04-30 09:29:13 +02:00
if (wasRunning)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
OnTaskCompleted(startTime, DateTime.UtcNow, TaskCompletionStatus.Aborted, null);
}
}
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
/// <summary>
/// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger.
/// </summary>
/// <param name="info">The info.</param>
/// <returns>BaseTaskTrigger.</returns>
/// <exception cref="ArgumentException">Invalid trigger type: + info.Type.</exception>
private ITaskTrigger GetTrigger(TaskTriggerInfo info)
{
var options = new TaskOptions
{
MaxRuntimeTicks = info.MaxRuntimeTicks
};
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
if (info.Type == TaskTriggerInfoType.DailyTrigger)
{
if (!info.TimeOfDayTicks.HasValue)
{
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
}
if (info.Type == TaskTriggerInfoType.WeeklyTrigger)
{
if (!info.TimeOfDayTicks.HasValue)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
}
2016-10-29 01:40:15 -04:00
2025-04-30 09:29:13 +02:00
if (!info.DayOfWeek.HasValue)
{
throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
}
if (info.Type == TaskTriggerInfoType.IntervalTrigger)
{
if (!info.IntervalTicks.HasValue)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
2016-10-29 01:40:15 -04:00
}
2025-04-30 09:29:13 +02:00
if (info.Type == TaskTriggerInfoType.StartupTrigger)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
return new StartupTrigger(options);
}
throw new ArgumentException("Unrecognized trigger type: " + info.Type);
}
/// <summary>
/// Disposes each trigger.
/// </summary>
private void DisposeTriggers()
{
foreach (var triggerInfo in InternalTriggers)
{
var trigger = triggerInfo.Item2;
trigger.Triggered -= OnTriggerTriggered;
trigger.Stop();
if (trigger is IDisposable disposable)
2016-10-29 01:40:15 -04:00
{
2025-04-30 09:29:13 +02:00
disposable.Dispose();
2016-10-29 01:40:15 -04:00
}
}
}
}