using Longbow.Tasks; using Microsoft.Extensions.Hosting; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Extensions.DependencyInjection { /// /// 后台任务扩展方法 /// internal static class TasksExtensions { /// /// 添加示例后台任务 /// /// public static IServiceCollection AddDemoTask(this IServiceCollection services) { services.AddHostedService(); return services.AddTaskServices(); } } /// /// 后台任务服务类 /// internal class TaskBackgroundServices : BackgroundService { /// /// 运行任务 /// /// /// 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; }); } }