c#quartz触发_[C#]使用Quartz.NET来创建定时工作任务

1 usingQuartz;2 usingQuartz.Impl;3 usingSystem;4 usingSystem.Threading;5

6 namespaceQuartzConsoleApp7 {8 classProgram9 {10 static void Main(string[] args)11 {12 //创建一个标准调度器工厂

13 ISchedulerFactory factory = newStdSchedulerFactory();14 //通过从标准调度器工厂获得一个调度器,用来启动任务

15 IScheduler scheduler =factory.GetScheduler();16 //调度器的线程开始执行,用以触发Trigger

17 scheduler.Start();18

19 //使用组别、名称创建一个工作明细,此处为所需要执行的任务

20 IJobDetail detail1 = JobBuilder.Create().WithIdentity("MyJob1", "MyGroup").Build();21 //通过使用UsingJobData添加传递到context(类型:IJobExecutionContext)的属性

22 IJobDetail detail2 = JobBuilder.Create().WithIdentity("MyJob2", "MyGroup").UsingJobData("Title","Hello World").23 UsingJobData("Pi",Math.PI).UsingJobData("Cnxy","http://www.cnc6.cn").Build();24 IJobDetail detail3 = JobBuilder.Create().WithIdentity("MyJob3", "MyGroup").Build();25 //使用组别、名称创建一个触发器,其中触发器立即执行,且每隔1秒或3秒执行一个任务,重复执行

26 ITrigger trigger1 = TriggerBuilder.Create().WithIdentity("MyTrigger1", "MyGroup").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever()).Build();27 ITrigger trigger2 = TriggerBuilder.Create().WithIdentity("MyTrigger2", "MyGroup").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever()).Build();28 ITrigger trigger3 = TriggerBuilder.Create().WithIdentity("MyTrigger3", "MyGroup").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever()).Build();29 //开始执行使用指定的触发器运行执行的工作任务

30 scheduler.ScheduleJob(detail1, trigger1);31 scheduler.ScheduleJob(detail2, trigger2);32 scheduler.ScheduleJob(detail3, trigger3);33 }34 }35 //运行并发运行

36 classMyFirstJob : IJob37 {38 public voidExecute(IJobExecutionContext context)39 {40 //JobDetail.Key:标识JobDetail的唯一ID41 //Trigger.Key:标识Trigger的唯一ID

42 Console.WriteLine($"1,现在时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}," +

43 $"工作明细:{context.JobDetail.Key.Name},工作触发器:{context.Trigger.Key.Name}");44 }45 }46 //运行并发运行

47 classMySecondJob : IJob48 {49 //获得值的方式:3、属性注入

50 public string Cnxy { set; get; }51 public voidExecute(IJobExecutionContext context)52 {53 //获得值的方式:1、通过IJobExecutionContext.JobDetail.JobDataMap["Key"]获得所对应的值

54 string value1 = (string)context.JobDetail.JobDataMap["Title"];55 //获得值的方式:2、也可以通过IJobExecutionContext.MergedJobDataMap["Key"]获得所对应的值

56 double value2 = (double)context.MergedJobDataMap["Pi"];57 Console.WriteLine($"2,现在时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}," +

58 $"Title:{value1},Pi:{value2},CNXY:{Cnxy}");59 }60 }61

62 //不运行并发运行

63 [DisallowConcurrentExecution]64 classMyThridJob : IJob65 {66 public voidExecute(IJobExecutionContext context)67 {68 Console.WriteLine($"3,现在时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");69 Thread.Sleep(3);70 }71 }72

73 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值