C#实现的调用Quartz.dll的定时任务插件

时间:2021-11-21 21:34:00

有两个cs文件。

第一个QuartzJob.cs 源码:

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

namespace SXF.Utils.QuartzScheduler
{
    /// <summary>
    /// 任务接口
    /// 优先使用Cron表达式,如果为空,则使用重复规则
    /// </summary>
    public class QuartzJob : IJob
    {
        //string JobName { get; }
        //string JobGroup { get; }
        /// <summary>
        /// Cron表达式
        /// </summary>
        public string CronExpression;
        /// <summary>
        /// 重复间隔
        /// </summary>
        public TimeSpan RepeatInterval;
        /// <summary>
        /// 重复次数
        /// </summary>
        public int RepeatCount;

        /// <summary>
        /// 执行的任务委托
        /// </summary>
        public event EventHandler DoWork;
        static object lockObj = new object();
        public void Execute(Quartz.JobExecutionContext context)
        {
            string name = context.JobDetail.Name;
            if (QuartzWorker.workCache[name])
            {
                EventLog.Log(DoWork.Target.GetType() + " 没运行完又自动触发,被忽略", "info");
                return;
            }
            QuartzWorker.workCache[name] = true;
            try
            {
                DoWork(null, null);
            }
            catch (Exception ero)
            {
                EventLog.Log(DoWork.Target.GetType() + " 执行出错:" + ero, true);
            }
            QuartzWorker.workCache[name] = false;
        }
    }
}

第二个QuartzWorker.cs 源码:

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

namespace SXF.Utils.QuartzScheduler
{
    /// <summary>
    /// QuartzWorker自动任务
    /// </summary>
    public class QuartzWorker
    {
        IScheduler scheduler;
        public QuartzWorker()
        {
            // 创建一个工作调度器工场
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            // 获取一个任务调度器
            scheduler = schedulerFactory.GetScheduler();
        }
        public static Dictionary<string, bool> workCache = new Dictionary<string, bool>();
        /// <summary>
        /// 添加一个任务
        /// </summary>
        /// <param name="job"></param>
        public void AddWork(QuartzJob job)
        {
            Type type = job.GetType();
            // 创建一个工作
            string jobName = "JobName_" + type;
            string jobGroup = "JobGroup_" + type;
            JobDetail jobDetail = new JobDetail(jobName, jobGroup, type);
            // 创建一个触发器
            Trigger trigger;
            //使用Cron表达式
            if (!string.IsNullOrEmpty(job.CronExpression))
            {
                CronTrigger cronTrigger = new CronTrigger();
                cronTrigger.CronExpression = new CronExpression(job.CronExpression);
                trigger = cronTrigger;
            }
            else//指定间隔次数
            {
                if (job.RepeatInterval.TotalSeconds == 0)
                    throw new Exception("job.RepeatInterval为0");
                if (job.RepeatCount == 0)
                    throw new Exception("job.RepeatCount为0");
                SimpleTrigger simpleTrigger = new SimpleTrigger();
                simpleTrigger.RepeatInterval = job.RepeatInterval;
                simpleTrigger.RepeatCount = job.RepeatCount;
                trigger = simpleTrigger;
            }
            trigger.Name = "trigger" + jobName;
            trigger.JobName = jobName;
            trigger.JobGroup = jobGroup;
            trigger.Group = "triggergroup" + jobName;
            scheduler.AddJob(jobDetail, true);
            DateTime ft = scheduler.ScheduleJob(trigger);
            workCache.Add(jobDetail.Name, false);
        }
        /// <summary>
        /// 开始运行
        /// </summary>
        public void Start()
        {
            scheduler.Start();
            EventLog.Info("QuartzWorker已启动");
        }
        /// <summary>
        /// 停止运行
        /// </summary>
        public void Stop()
        {
            scheduler.Shutdown(true);
            EventLog.Info("QuartzWorker已停止");
        }
    }
}

引用的Quartz.dll是1.0版本的。

global.asax中调用方法:

static QuartzWorker worker;
		protected void Application_Start(Object sender, EventArgs e)
		{
             

            worker = new QuartzWorker();
			NewsUpdateWork newsWork = new NewsUpdateWork();			
			worker.AddWork(newsWork);
			worker.Start();
		   
		}

protected void Application_End(Object sender, EventArgs e)
		{
			//在应用程序关闭时运行的代码
			if (worker != null)
			{
				worker.Stop();
			}
		}

newsupdatework.cs的写法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SXF.Utils;
using SXF.Utils.QuartzScheduler;

namespace xxx.Facade.Task
{
    /// <summary>
    /// news表当isupdate=0时,自动重新生成新闻静态页面
    /// </summary>
    public class NewsUpdateWork : QuartzJob
    {
        public NewsUpdateWork()
        {

            //CronExpression = "0 0/1 * * * ?";
            //每天21点-24点,0点-7点,每隔5分钟执行一次
            //CronExpression = "0 0/5 18-23,0-9 * * ?";
            CronExpression = "0 0/5 * * * ?";
            RepeatInterval = new TimeSpan(0, 0, 0);
            RepeatCount = 0;
            DoWork += new EventHandler(this_DoWork);
        }
        public void this_DoWork(object sender, EventArgs e)
        {
           //这里写你要处理的定时任务
        }
    }
}