增加后台任务同步执行方法

This commit is contained in:
falcon 2022-07-14 10:14:46 +08:00
parent 1a5da57187
commit 1983778d22
2 changed files with 41 additions and 9 deletions

View File

@ -41,11 +41,11 @@ namespace Falcon.SugarApi.Test
}
public override float RunTimespan => 1;
protected async override Task RunAsync() {
protected async override Task<bool> RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:BackTaskAsync Run!");
//Thread.Sleep(3 * 1000);
await Task.Delay(new TimeSpan(0,0,3));
await Task.CompletedTask;
return true;
}
}
@ -76,9 +76,14 @@ namespace Falcon.SugarApi.Test
base.OnCompleted(t);
}
protected override Task RunAsync() {
protected override Task<bool> RunAsync() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test RunAsync!");
return Task.FromResult(true);
}
protected override bool Run() {
this.Log.LogInformation($"{DateTime.Now.ToString("HH:mm:ss")}:Test Run!");
return Task.CompletedTask;
return true;
}
}

View File

@ -11,9 +11,15 @@ namespace Falcon.SugarApi.BackTask
public abstract class BackgroundLongTask : BackgroundService, IDisposable
{
/// <summary>
/// 要执行的任务
/// 要执行的任务,异步。
/// </summary>
protected abstract Task RunAsync();
/// <returns>继续执行True退出False</returns>
protected virtual Task<bool> RunAsync() { return Task.FromResult(false); }
/// <summary>
/// 要执行的任务,同步。
/// </summary>
/// <returns>继续执行True退出False</returns>
protected virtual bool Run() { return false; }
/// <summary>
/// 执行时间间隔,秒
/// </summary>
@ -36,7 +42,11 @@ namespace Falcon.SugarApi.BackTask
protected virtual void OnException(BackgroundLongTask t, Exception ex) { }
/// <summary>
/// 用于定期执行任务的委托
/// 用于定期执行任务的委托,异步
/// </summary>
private Action actionAsync;
/// <summary>
/// 用于定期执行任务的委托,同步
/// </summary>
private Action action;
@ -46,13 +56,15 @@ namespace Falcon.SugarApi.BackTask
/// 构造一个后台长期任务
/// </summary>
public BackgroundLongTask() {
action = async () => {
actionAsync = async () => {
OnStart(this);
while (!TokenSource.Token.IsCancellationRequested) {
await Task.Delay(TimeSpan.FromSeconds(RunTimespan))
.ContinueWith(async _ => {
try {
await RunAsync();
if (!await RunAsync()) {
TokenSource.Cancel();
}
}
catch (Exception ex) {
OnException(this, ex);
@ -62,6 +74,20 @@ namespace Falcon.SugarApi.BackTask
}
OnStop(this);
};
action = () => {
OnStart(this);
while (!TokenSource.Token.IsCancellationRequested) {
Thread.Sleep(TimeSpan.FromSeconds(RunTimespan));
try {
if (!Run()) break;
OnCompleted(this);
}
catch (Exception ex) {
OnException(this, ex);
}
}
OnStop(this);
};
}
/// <summary>
/// 服务器启动时执行
@ -69,6 +95,7 @@ namespace Falcon.SugarApi.BackTask
/// <param name="stoppingToken">退出信号</param>
/// <returns></returns>
protected override Task ExecuteAsync(CancellationToken stoppingToken) {
_ = Task.Factory.StartNew(actionAsync, stoppingToken);
_ = Task.Factory.StartNew(action, stoppingToken);
return Task.CompletedTask;
}