隐藏

C#集成使用Quartz.NET详解

发布:2023/3/22 21:09:33作者:管理员 来源:本站 浏览次数:699

版本:.net framework 4.6.1


Quartz.net:Quartz Scheduling Framework for .NET 3.2.4


首先使用VS 创建工程->NuGet 中引用Quartz;


使用Quartz分为五步:

<1> 创建一个ISchedulerFactory,然后并且获取 Scheduler


           ISchedulerFactory schedFact = new StdSchedulerFactory();


           IScheduler sched = await schedFact.GetScheduler();

<2>  启动 Scheduler


           await sched.Start();

<3>  创建 job 任务


IJobDetail job = JobBuilder.Create<SimpleJob>()


                   .WithIdentity("job1", "group1")


                   .Build();

<4>  创建 trigger 触发器


【1】构造一个在特定时间执行,无重复的 trigger:


// trigger builder creates simple trigger by default, actually an ITrigger is returned


ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create()


   .WithIdentity("trigger1", "group1")


   .StartAt(myStartTime) // some Date


   .ForJob("job1", "group1") // identify job with name, group strings


   .Build();


【2】构造一个在特定时间执行, 每10秒重复一次的 trigger:


trigger = TriggerBuilder.Create()


   .WithIdentity("trigger3", "group1")


   .StartAt(myTimeToStartFiring) // if a start time is not given (if this line were omitted), "now" is implied


   .WithSimpleSchedule(x => x


       .WithIntervalInSeconds(10)


       .WithRepeatCount(10)) // note that 10 repeats will give a total of 11 firings


   .ForJob(myJob) // identify job with handle to its JobDetail itself                


   .Build();


【3】构造一个在接下来的五分钟内执行一次的 trigger:


trigger=(ISimpleTrigger)TriggerBuilder.Create()


.WithIdentity("trigger5","group1")


.StartAt(DateBuilder.FutureDate(5,IntervalUnit.Minute))// use DateBuilder to create a date in the future


.ForJob(myJobKey)// identify job with its JobKey


.Build();


【4】构造一个立刻执行, 然后在 22:00 前每五分钟重复一次的 trigger:


trigger=TriggerBuilder.Create()


.WithIdentity("trigger7","group1")


.WithSimpleSchedule(x=>x


.WithIntervalInMinutes(5)


.RepeatForever())


.EndAt(DateBuilder.DateOf(22,0,0))


.Build();

<5> 使用trigger规划执行任务job


await sched.ScheduleJob(job, trigger);


待执行的任务:


   public class SimpleJob : IJob


   {


       [MethodImpl(MethodImplOptions.Synchronized)]


       public virtual Task Execute(IJobExecutionContext context)


       {


           LogHelper.WriteLog("start ");


           Thread.Sleep(10000);


           LogHelper.WriteLog("end ");


           return Console.Out.WriteLineAsync($"job工作了 在{DateTime.Now}");


       }


   }