08_Quartz.NET使用

Quartz.NET 是一个用于调度任务和作业的开源框架,它允许开发人员创建简单或复杂的调度方案,例如定时执行任务,定时触发作业等。

创建调度器很简单需要三个对象:  IScheduler、IJob、ITrigger,直接上代码,使用可根据需求再扩展

using Quartz;
using Quartz.Impl;
using QuartzScheduler.Job;
using QuartzScheduler.Listener;

namespace QuartzScheduler
{
    /// <summary>
    /// 调度器
    /// </summary>
    public class MyScheduler
    {
        /// <summary>
        /// 创建调度器
        /// </summary>
        public async static Task SchedulerAction()
        {
            //IScheduler
            StdSchedulerFactory stdScheduler = new StdSchedulerFactory();
            IScheduler scheduler = await stdScheduler.GetScheduler();
            await scheduler.Start();

            //添加监听器
            scheduler.ListenerManager.AddJobListener(new JobListener());//Job监听器
            scheduler.ListenerManager.AddTriggerListener(new TriggerListener());//Trigger监听器
            scheduler.ListenerManager.AddSchedulerListener(new SchedulerListener());//Scheduler监听器

            //IJob
            IJobDetail jobDetail = JobBuilder.Create<QuartzJobDemo01>()
                .WithIdentity("JobName", "Group01")                                       //唯一标识
                .WithDescription("这里是描述......")                                      //信息描述
                .StoreDurably(true)                                                       //孤立存储
                .RequestRecovery(true)                                                    //请求恢复,指应用崩溃后再次启动,会重新执行该作业
                .Build();

            //IJob设置参数
            jobDetail.JobDataMap.Add("UserName1", "张三");
            jobDetail.JobDataMap.Add("Weight", 100);
            jobDetail.JobDataMap.Add("time", DateTime.Now);


            //ITrigger
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("TriggerName", "Group01")
                //.StartAt(new DateTimeOffset())                 //从某时间段开始执行
                //.StartNow()                                  //从现在开始

                //链式策略
                //.WithSimpleSchedule(p =>
                //{
                //    p.WithIntervalInSeconds(5)        //5秒执行一次,(WithIntervalInHours小时,WithIntervalInMinutes分钟)
                //    //.WithRepeatCount(3)             //执行3次
                //    .RepeatForever();                 //一直执行      

                //正则表达式策略
                .WithCronSchedule("0/5 * * * * ? ")    //每5秒执行一次:https://cron.ciding.cc/在线正则解析
                .Build();

            // ITrigger设置参数
            trigger.JobDataMap.Add("Age", 18);


            //添加调度
            await scheduler.ScheduleJob(jobDetail, trigger);


        }
    }
}

 

QuartzJobDemo01.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Job
{
    /// <summary>
    /// 任务01
    /// </summary>
    [PersistJobDataAfterExecution]//执行后保留作业数据
    [DisallowConcurrentExecution]//确保上次执行完成后才能执行这次
    public class QuartzJobDemo01 : IJob
    {
        public QuartzJobDemo01()
        {
            Console.WriteLine("--QuartzJobDemo01被构造了-");
        }

        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Factory.StartNew(() =>
            {
                string? username01= context.JobDetail.JobDataMap.GetString("UserName1"); 
                int? weight = context.JobDetail.JobDataMap.GetInt("Weight");
                string? time = context.JobDetail.JobDataMap.GetDateTime("time").ToString();
                int? age = context.Trigger.JobDataMap.GetInt("Age");
                Console.WriteLine("--------------------------------------");
                Console.WriteLine($"Hello,这是QuartzJobDemo01...........");
                Console.WriteLine($"传过来的参数UserName01:{username01}");
                Console.WriteLine($"传过来的参数Weight:{weight}");
                Console.WriteLine($"传过来的参数time:{time}");
                Console.WriteLine($"传过来的参数Age:{age}");

                context.JobDetail.JobDataMap.Put("Weight", weight + 1);//保留作业数据测试
                Console.WriteLine("--------------------------------------");
            });
        }
    }
}

 

JobListener.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Listener
{
    /// <summary>
    /// Job监听器
    /// </summary>
    public class JobListener : IJobListener
    {
        public string Name => "JobListener的名称";

        /// <summary>
        /// 任务中断后执行
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("任务中断后执行..........."));
        }

        /// <summary>
        /// 执行前触发
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("执行前触发..........."));
        }

        /// <summary>
        /// 执行后会触发
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException? jobException, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>Console.WriteLine("执行后会触发..........."));
        }
    }
}

 

TriggerListener.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Listener
{
    /// <summary>
    /// Trigger监听器
    /// </summary>
    public class TriggerListener : ITriggerListener
    {
        public string Name => "TriggerListener名称";

        /// <summary>
        /// 在JobListener触发完再触发
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="triggerInstructionCode"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("TriggerListener---->TriggerComplete,在JobListener触发完再触发..........."));
            Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("");
        }

        /// <summary>
        /// 在JobListener触发前触发
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async  Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("TriggerListener---->TriggerFired,在JobListener触发前触发 ..........."));
        }

        public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("TriggerListener---->TriggerMisfired ..........."));
        }

        /// <summary>
        /// 返回true取消执行,false继续执行
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            //返回true 只会执行TriggerFired方法
            return await Task.Run(() => {
                return false;
            });
        }
    }
}

 

SchedulerListener.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Listener
{
    /// <summary>
    ///  Scheduler监听器   https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/scheduler-listeners.html
    /// </summary>
    public class SchedulerListener : ISchedulerListener
    {
        /// <summary>
        /// Job被添加时
        /// </summary>
        /// <param name="jobDetail"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobAdded(IJobDetail jobDetail, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobAdded ******{jobDetail.Key.Name}"));
        }

        public async Task JobDeleted(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobDeleted ******{jobKey.Name}"));
        }

        public async Task JobInterrupted(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobInterrupted ******{jobKey.Name}"));
        }

        public async Task JobPaused(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobPaused ******{jobKey.Name}"));
        }

        public async Task JobResumed(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobResumed ******{jobKey.Name}"));
        }

        public async Task JobScheduled(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobScheduled ******{trigger.Key.Name}"));
        }

        public async Task JobsPaused(string jobGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobsPaused ******{jobGroup}"));
        }

        public async Task JobsResumed(string jobGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobsResumed ******{jobGroup}"));
        }

        public async Task JobUnscheduled(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobUnscheduled ******{triggerKey.Name}"));
        }

        public async Task SchedulerError(string msg, SchedulerException cause, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerError ******{msg}"));
        }

        public async Task SchedulerInStandbyMode(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerInStandbyMode ******"));
        }

        public async Task SchedulerShutdown(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerShutdown ******"));
        }

        public async Task SchedulerShuttingdown(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerShuttingdown ******"));
        }

        public async Task SchedulerStarted(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerStarted ******"));
        }

        public async Task SchedulerStarting(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerStarting ******"));
        }

        public async Task SchedulingDataCleared(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulingDataCleared ******"));
        }

        public async Task TriggerFinalized(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggerFinalized ******{trigger.Key.Name}"));
        }

        public async Task TriggerPaused(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggerPaused ******{triggerKey.Name}"));
        }

        public async Task TriggerResumed(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggerResumed ******{triggerKey.Name}"));
        }

        public async Task TriggersPaused(string? triggerGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggersPaused ******{triggerGroup}"));
        }

        public async Task TriggersResumed(string? triggerGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggersResumed ******{triggerGroup}"));
        }
    }
}

 

调用

internal class Program
    {
        static void Main(string[] args)
        {
            MyScheduler.SchedulerAction().GetAwaiter().GetResult();

            Console.Read();
        }
    }

 

posted @ 2024-05-09 14:07  野码  阅读(105)  评论(0编辑  收藏  举报