MasstransferExporter/MasstransferCommon/Scheduler/DelayScheduler.cs

42 lines
1.2 KiB
C#
Raw Permalink Normal View History

2024-09-05 13:25:51 +00:00
using Serilog;
namespace MasstransferCommon.Scheduler;
2024-06-19 07:53:34 +00:00
/// <summary>
/// 延时定时任务
/// </summary>
public class DelayScheduler
{
2024-09-05 13:25:51 +00:00
/// <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)
2024-06-19 07:53:34 +00:00
{
2024-09-05 13:25:51 +00:00
try
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (delay.TotalMilliseconds < 0)
throw new ArgumentOutOfRangeException(nameof(delay), "延时时间不能为负数");
2024-06-19 07:53:34 +00:00
2024-09-05 13:25:51 +00:00
await Task.Delay(delay, cancellationToken);
if (cancellationToken.IsCancellationRequested)
{
return;
}
action();
}
catch (Exception e)
{
if (e is not TaskCanceledException)
{
Log.Error(e, "延时任务执行失败");
}
}
2024-06-19 07:53:34 +00:00
}
}