在日常开发中,使用Quartz来做定时任务非常常见,每天凌晨自动拉去数据做报表等功能,大家呢也都是习惯了硬编码,使用的都是cron表达式,但是在新写一个功能的时候,需要手动写一个接口去触发这个任务,因为定时的时间没有到点,然后手动触发的参数可能还有 自动定时任务条件不同,于是基于quartz封装了个组件用来管理和支持手动触发提供UI界面管理。
<PackageReference Include="Qin.TaskJobManage" Version="1.0.4" />
public void ConfigureServices(IServiceCollection services) { services.AddTaskJobMiddleware(a=> { // Route 主页地址,默认是 /TaskJobUI // LoadAssemblyName job所在的程序集名称,默认在当前web启动程序集 // SelfTurnOn 程序启动运行任务 }); } public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime) { lifetime.ApplicationStarted.Register(() => app.ApplicationServices.StartTaskJob());// 定时任务在程序启动后自动运行 app.UseTaskJobMiddleware(); // 要在 app.UseRouting(); 之前 }
public class Job1 : TaskModel, IJob { public override void Config() { status = 0; taskName = "测试任务a"; groupName = "分组a"; describe = "每10秒执行一次"; cron = "0/10 * * * * ? "; Job = typeof(Job1); } public override TriggerBuilder ConfigTrigger(TriggerBuilder triggerbuilder) { return triggerbuilder; } public Task Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; Console.WriteLine(dataMap.GetString("parms") ?? ""); string json = context.Trigger.JobDataMap.GetString("parms") ?? ""; Console.WriteLine("动态传参数是:" + json); return Task.Run(() => { //int p = 0; //var a = 12 / p; ConsoleExcept.WriteLine("Hello-" + DateTime.Now.ToString("HH:mm:ss"), ConsoleColor.Red); }); //return Task.CompletedTask; } }
http://localhost:xxx/TaskJobUI/
实现 IJobExecutionLogs
public class JobExecutionLog : IJobExecutionLogs { public Task<ResultMsg> GetJobExecutionLog(TaskModel parms, int pageIndex, int pageSize) { List<TaskModel> list = new List<TaskModel>(); list.Add(new TaskModel() { status = 0, taskName = "测试任务a", groupName = "分组a", describe = "每10秒执行一次", cron = "0/10 * * * * ? " }); if (!string.IsNullOrWhiteSpace(parms.taskName)) { list = list.Where(a=>a.taskName == parms.taskName).ToList(); } if (!string.IsNullOrWhiteSpace(parms.groupName)) { list = list.Where(a => a.groupName == parms.groupName).ToList(); } return Task.FromResult(new ResultMsg { msg = $"pageIndex={pageIndex},pageSize={pageSize},taskName={parms.taskName},groupName={parms.groupName}", status = true, data = new TableList<TaskModel>() { Count = list.Count(), TableData = list.Skip(pageIndex == 1 ? 0 : 1).Take(pageSize) } }); } }