Quartz Demo 任务调度程序简单Demo

发布时间 2024-01-04 16:46:42作者: EasyBI

创建Windows 控制台应用程序 ,  .net framework 版本 4.5.2

Nuget . Quartz 版本 用 2.5 

 

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


/// <summary>
/// 1. .Net Framework = 4.5.2
/// 2. Quartz  = 2.5 
/// </summary>
namespace QuartzDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //从工厂中获取一个调度器实例化
            IScheduler scheduler = (IScheduler)StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();       //开启调度器

            JobBuilder.Create();
            IJobDetail job1 = JobBuilder.Create(Type.GetType("QuartzDemo.HelloJob")).WithIdentity("作业名称", "作业组").Build();

            ITrigger trigger1 = TriggerBuilder.Create()
                                        .WithIdentity("触发器名称", "触发器组")
                                        .StartNow()     //现在开始
                                        .WithCronSchedule("0/5 * * * * ?").Build();  //触发时间,5秒一次。

            //注册Listener , 所有Job都会起作用
            var action = new Action<string>(Program.NotifyExecuteMessage);
            scheduler.ListenerManager.AddJobListener(new MyListenere(action));

            scheduler.ScheduleJob(job1, trigger1);      //把作业,触发器加入调度器。
        }
        public static void NotifyExecuteMessage(string msg)
        {
            Console.WriteLine("任务执行完成 :" + msg);
        }
    }

    public class HelloJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("作业执行JOB TEST!");
        }


    }
    public class MyListenere : IJobListener
    {
        public Action<string> NotifyExecute;
        public MyListenere(Action<string> action)
        {
            this.NotifyExecute = action;
        }
        string IJobListener.Name
        {
            get
            {
                return "Myjob";
            }
        }

        void IJobListener.JobExecutionVetoed(IJobExecutionContext context)
        {
            Console.WriteLine("MyJobListener.JobExecutionVetoed()");
        }

        void IJobListener.JobToBeExecuted(IJobExecutionContext context)
        {
            Console.WriteLine("MyJobListener.jobToBeExecuted()");
        }

        void IJobListener.JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
        {

            string msg = jobException == null ? context.JobDetail.JobType.FullName : jobException.Message;

            NotifyExecute(msg);
        }
    }

}