fix(#IZOW4): 增加TasksExtensions扩展任务示例

#Comment
comment #IZOW4
增加 TasksExtensions 扩展方法,调用 services.AddHostedService<TaskBackgroundServices>()

#Issue
close https://gitee.com/LongbowEnterprise/dashboard/issues?id=IZOW4
This commit is contained in:
Argo Zhang 2019-07-25 10:03:17 +08:00
parent c666afc54d
commit fcb50ffda4
No known key found for this signature in database
GPG Key ID: 152E398953DDF19F
3 changed files with 46 additions and 6 deletions

View File

@ -21,11 +21,6 @@ namespace Bootstrap.Admin.Controllers.Api
[HttpGet]
public IEnumerable<object> Get()
{
TaskServicesManager.GetOrAdd("单次任务", token => Task.Delay(1000));
TaskServicesManager.GetOrAdd("周期任务", token => Task.Delay(1000), TriggerBuilder.Build(Cron.Secondly(5)));
TaskServicesManager.GetOrAdd("超时任务", token => Task.Delay(2000), TriggerBuilder.Default.WithTimeout(1000).WithInterval(1000).WithRepeatCount(2).Build());
TaskServicesManager.GetOrAdd("故障任务", token => throw new Exception("故障任务"));
TaskServicesManager.GetOrAdd("取消任务", token => Task.Delay(1000)).Triggers.First().Enabled = false;
return TaskServicesManager.ToList().Select(s => new { s.Name, Status = s.Status.ToString(), s.LastRuntime, s.CreatedTime, s.NextRuntime, LastRunResult = s.Triggers.First().LastResult.ToString(), TriggerExpression = s.Triggers.FirstOrDefault().ToString() }).OrderBy(s => s.Name);
}
}

View File

@ -63,7 +63,7 @@ namespace Bootstrap.Admin
services.AddBootstrapAdminAuthentication();
services.AddSwagger();
services.AddButtonAuthorization();
services.AddTaskServices();
services.AddDemoTask();
services.AddMvc(options =>
{
options.Filters.Add<BootstrapAdminAuthorizeFilter>();

View File

@ -0,0 +1,45 @@
using Longbow.Tasks;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// 后台任务扩展方法
/// </summary>
internal static class TasksExtensions
{
/// <summary>
/// 添加示例后台任务
/// </summary>
/// <param name="services"></param>
public static IServiceCollection AddDemoTask(this IServiceCollection services)
{
services.AddHostedService<TaskBackgroundServices>();
return services.AddTaskServices();
}
}
/// <summary>
/// 后台任务服务类
/// </summary>
internal class TaskBackgroundServices : BackgroundService
{
/// <summary>
/// 运行任务
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.Run(() =>
{
TaskServicesManager.GetOrAdd("单次任务", token => Task.Delay(1000));
TaskServicesManager.GetOrAdd("周期任务", token => Task.Delay(1000), TriggerBuilder.Build(Cron.Secondly(5)));
TaskServicesManager.GetOrAdd("超时任务", token => Task.Delay(2000), TriggerBuilder.Default.WithTimeout(1000).WithInterval(1000).WithRepeatCount(2).Build());
TaskServicesManager.GetOrAdd("故障任务", token => throw new Exception("故障任务"));
TaskServicesManager.GetOrAdd("取消任务", token => Task.Delay(1000)).Triggers.First().Enabled = false;
});
}
}