Quartz.net使用笔记

一、需求场景:每天固定时间执行某个行为/动作。

  一开始想用定时器,后来无意间发现了这个插件,感觉功能太强大了,完美解决了我的问题。

二、下载地址:https://www.quartz-scheduler.net/

三、使用方法

  1.将刚才下载的热乎乎的dll引入到你的项目中

  2.先写你想定时执行的任务

1         public class ModifiyStateJob : IJob
2         {
3             Task IJob.Execute(IJobExecutionContext context)
4             {
5                 Console.WriteLine("现在的时间是--{1}", DateTime.Now.ToString());
6                 return null;
7             }
8         }

  3.用Quartz设置在每天的19:53执行该任务

 1         public static async Task ListenTime()
 2         {
 3             try
 4             {
 5                 // Grab the Scheduler instance from the Factory
 6                 NameValueCollection props = new NameValueCollection
 7                 {
 8                     { "quartz.serializer.type", "binary" }
 9                 };
10                 StdSchedulerFactory factory = new StdSchedulerFactory(props);
11                 IScheduler scheduler = await factory.GetScheduler();
12 
13                 // and start it off
14                 await scheduler.Start();
15 
16                 // define the job and tie it to our HelloJob class
17                 //
18                 IJobDetail job1 = JobBuilder.Create<TimeJob>()
19                     .WithIdentity("job1", "group1")
20                     .Build();
21 
22 
24                 //每天的19点53分执行  时间的顺序是秒 分 小时 不要写错哦
25                 ITrigger trigger1 = TriggerBuilder.Create()
26                     .WithIdentity("trigger1", "group1")
27                     .StartNow().WithCronSchedule("0 53 19 * * ?")
28                     .Build();
29 
30                 // Tell quartz to schedule the job using our trigger
31                 await scheduler.ScheduleJob(job1, trigger1);
32 
33                 // some sleep to show what's happening
34                 // await Task.Delay(TimeSpan.FromSeconds(60));
35 
36                 // and last shut down the scheduler when you are ready to close your program
37                 //   await scheduler.Shutdown();
38             }
39             catch (SchedulerException se)
40             {
41                 Console.WriteLine(se);
42             }
43 
44 
45         }

  4.在入口处进行调用

1         static void Main(string[] args)
2         {
3             ListenTime().GetAwaiter().GetResult();
4             Console.Read();
5         }

  5.效果(如果程序不关,则每天的19:53分都会运行该程序,在控制台进行打印)

写在后面的话:我只是用了Quartz的一个小功能,无论你是想固定时间执行任务,还是间隔多长时间执行任务等等,Quartz.net都能满足你的需求,只要按照指定的规则编写就可以啦。

猜你喜欢

转载自www.cnblogs.com/jas0203/p/10158546.html