在MVC项目中简单实现定时任务
emmm,之前因为项目的原因,得用到定时任务,没有使用Quartz.net跟Hangfire
而是直接在startup文件下ConfigureServices中注入如下代码:
//定时任务 var provider = services.BuildServiceProvider(); TaskSchedulerService.RegisterTask(provider).Wait();
而在项目的Service层中加入文件TaskSchedulerService.cs
1 /// <summary> 2 /// 定时任务 3 /// </summary> 4 public static class TaskSchedulerService 5 { 6 /// <summary> 7 /// 依赖注入 8 /// </summary> 9 public static ServiceProvider serviceProvider; 10 11 /// <summary> 12 /// 任务调度器 13 /// </summary> 14 private static IScheduler scheduler; 15 16 17 /// <summary> 18 /// 开始任务 19 /// </summary> 20 static TaskSchedulerService() 21 { 22 NameValueCollection props = new NameValueCollection 23 { 24 { 25 "quartz.serializer.type", "binary" 26 } 27 }; 28 var schedulerFactory = new StdSchedulerFactory(props); 29 scheduler = schedulerFactory.GetScheduler().Result; 30 scheduler.Start().Wait(); 31 } 32 33 /// <summary> 34 /// 注册任务 35 /// </summary> 36 /// <param name="_serviceProvider">依赖注入</param> 37 /// <returns></returns> 38 public static async Task RegisterTask(ServiceProvider _serviceProvider) 39 { 40 serviceProvider = _serviceProvider; 41 42 //协议到期(每天凌晨两点执行一次) 43 //创建作业和触发器 44 var contratJobDetail = JobBuilder.Create<ContractMessageTask>().Build(); 45 var contratTrigger = TriggerBuilder.Create() 46 .WithCronSchedule("0 0 2 * * ?") 47 .Build(); 48 //添加调度 49 await scheduler.ScheduleJob(contratJobDetail, contratTrigger); 50 } 51 } 52 53 /// <summary> 54 /// 协议到期通知 55 /// </summary> 56 public class ContractMessageTask : IJob 57 { 58 public Task Execute(IJobExecutionContext context) 59 { 60 return Task.Run(() => 61 { 62 try 63 { 64 Logs.Info("协议到期通知定时任务开始。"); 65 var _MessageService = TaskSchedulerService.serviceProvider.GetService<IMessageService>(); 66 _MessageService.ContractMessageTask().Wait(); 67 Logs.Info("协议到期通知定时任务完成。"); 68 } 69 catch (Exception e) 70 { 71 Logs.Error(e.GetMsgDetail("协议到期通知定时任务错误:")); 72 throw e; 73 } 74 }); 75 } 76 }
就可以很简便的实现定时任务啦,目前任务量不大的情况下运行还是挺稳定的