42 lines
1.2 KiB
C#
42 lines
1.2 KiB
C#
using Serilog;
|
|
|
|
namespace MasstransferCommon.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)
|
|
{
|
|
if (e is not TaskCanceledException)
|
|
{
|
|
Log.Error(e, "延时任务执行失败");
|
|
}
|
|
}
|
|
}
|
|
} |