Dispenser/DispenserCommon/Scheduler/DelayScheduler.cs

39 lines
1.1 KiB
C#

using Serilog;
namespace DispenserCommon.Scheduler;
/// <summary>
/// 延时定时任务
/// </summary>
public class DelayScheduler
{
/// <summary>
/// 设定延时任务
/// </summary>
/// <param name="action"></param>
/// <param name="delay"></param>
/// <param name="cancellationToken"></param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static async void Delay(Action action, TimeSpan delay, CancellationToken cancellationToken = default)
{
try
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (delay.TotalMilliseconds < 0)
throw new ArgumentOutOfRangeException(nameof(delay), "延时时间不能为负数");
await Task.Delay(delay, cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
return;
}
action();
}
catch (Exception e)
{
Log.Error(e, "延时任务执行失败");
}
}
}