自定义定时任务,代码逻辑调整
This commit is contained in:
@@ -110,7 +110,7 @@ namespace Tnb.WarehouseMgr
|
||||
private Task TimedTask(Func<CancellationTokenSource, Task> action, CancellationTokenSource cts, int interval, TimeSpanUnit timeType = TimeSpanUnit.Seconds)
|
||||
{
|
||||
var token = cts.Token;
|
||||
return Task.Run(async () =>
|
||||
return Task.Factory.StartNew(async () =>
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
@@ -135,7 +135,37 @@ namespace Tnb.WarehouseMgr
|
||||
});
|
||||
await TaskDelay(timeType, interval);
|
||||
}
|
||||
}, token);
|
||||
}, cts.Token, TaskCreationOptions.None, new CustomerTaskScheduler());
|
||||
|
||||
#region ThreadPool 线程运行会导致线程饥饿
|
||||
//return Task.Run(async () =>
|
||||
//{
|
||||
// while (!token.IsCancellationRequested)
|
||||
// {
|
||||
|
||||
// await action(cts).Catch(async ex =>
|
||||
// {
|
||||
// if (ex is TimedTaskException timedTaskEx and not null)
|
||||
// {
|
||||
// await _eventPublisher.PublishAsync(new LogEventSource("Log:CreateExLog", timedTaskEx.options!, new SysLogEntity
|
||||
// {
|
||||
// Id = SnowflakeIdHelper.NextId(),
|
||||
// Category = 4,
|
||||
// UserId = timedTaskEx.UserId,
|
||||
// UserName = timedTaskEx.UserName,
|
||||
// IPAddress = NetHelper.Ip,
|
||||
// RequestURL = timedTaskEx.RequestURL,
|
||||
// RequestMethod = timedTaskEx.RequestMethod,
|
||||
// Json = timedTaskEx + "\n" + timedTaskEx.InnerException?.StackTrace + "\n" + timedTaskEx?.TargetSite?.GetParameters().ToString(),
|
||||
// //PlatForm = string.Format("{0}-{1}", userAgent.OS.ToString(), userAgent.RawValue),
|
||||
// CreatorTime = DateTime.Now
|
||||
// }));
|
||||
// }
|
||||
// });
|
||||
// await TaskDelay(timeType, interval);
|
||||
// }
|
||||
//}, token);
|
||||
#endregion
|
||||
}
|
||||
|
||||
private Task TaskDelay(TimeSpanUnit timeType, int interval)
|
||||
@@ -153,4 +183,43 @@ namespace Tnb.WarehouseMgr
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 自定义任务调度器,保证长任务在单独的线程中运行
|
||||
/// </summary>
|
||||
internal class CustomerTaskScheduler : TaskScheduler
|
||||
{
|
||||
// 这边的 BlockingCollection 只是举个例子,如果是普通的队列,配合锁也是可以的。
|
||||
private readonly BlockingCollection<Task> _tasks = new BlockingCollection<Task>();
|
||||
|
||||
public CustomerTaskScheduler()
|
||||
{
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
foreach (var task in _tasks.GetConsumingEnumerable())
|
||||
{
|
||||
TryExecuteTask(task);
|
||||
}
|
||||
})
|
||||
{
|
||||
IsBackground = true
|
||||
};
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
protected override IEnumerable<Task> GetScheduledTasks()
|
||||
{
|
||||
return _tasks;
|
||||
}
|
||||
|
||||
protected override void QueueTask(Task task)
|
||||
{
|
||||
_tasks.Add(task);
|
||||
}
|
||||
|
||||
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user