MasstransferExporter/MasstransferCommon/Scheduler/JobScheduler.cs

44 lines
1.1 KiB
C#

using System.Collections.Concurrent;
using Serilog;
namespace MasstransferCommon.Scheduler;
public class JobScheduler
{
private static readonly ConcurrentDictionary<string, ExecuteTask> Tasks = new();
/// <summary>
/// 添加调度任务
/// </summary>
/// <param name="name"></param>
/// <param name="action"></param>
/// <param name="interval"></param>
/// <param name="delay"></param>
public static void AddTask(string name, Action action, int interval = 100, int delay = 0)
{
try
{
if (Tasks.ContainsKey(name)) return;
if (delay > 0)
{
Thread.Sleep(delay);
}
Tasks[name] = new ExecuteTask(name, action, interval);
}
catch (Exception e)
{
Log.Error(e, $"添加 {name} 任务失败");
}
}
/// <summary>
/// 移除任务
/// </summary>
/// <param name="name"></param>
public static void RemoveTask(string name)
{
if (Tasks.TryRemove(name, out var task)) task.Dispose();
}
}