quartz(开源项目)

 * Quartz.NET

1. 各类

1.1. scheduler

  - 用 ISchedulerFactory进行实例化

  - 实例化后启动Start(),即处于等待模式,可以通过add和remove方法添加移除Jobs和Triggers以及它调度相关的操作

  - 关闭后,将不能再重启使用,除非再实例化新的scheduler

  - 生命周期:SchedulerFactory创建开始→Shutdown()结束

1.2. IJob

  - 定义scheduler的执行内容

1.3. IJobDetail

  - 定义Jobs实例

1.4. ITtrigger

  - 定义scheduler怎么去执行Job

1.5. JobBuilder

  - 定义JobDetail实例

1.6 TriggerBuilder

  - 定义和构建Trigger实例

 

二、使用配置文件执行任务

  quartz 2.6.0版本,读取xml配置文件,定时执行job

class Program
    {
        static void Main(string[] args)
        {
            SendBootstrapper boot = new SendBootstrapper();
            boot.Initialize();
            boot.Start();
            Console.ReadKey();
        }
    }


using Quartz;
using Quartz.Impl;
using Quartz.Simpl;
using Quartz.Xml;
using System.ComponentModel.Composition;
 /// <summary>
     /// 所有定时计算服务
     /// </summary>
    [Export(typeof(IBootstrapper))]
    public class SendBootstrapper : IBootstrapper
    {
        private readonly XMLSchedulingDataProcessor _processor;
        private readonly IScheduler _scheduler;

        /// <summary>
        /// job调度
        /// </summary>
        public SendBootstrapper()
        {
            _processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
            ISchedulerFactory sf = new StdSchedulerFactory();

            _scheduler = sf.GetScheduler();


        }

        public void Initialize()
        {

            _processor.ProcessFileAndScheduleJobs("~/quartz_jobs.xml", _scheduler);
            LogHelper.Info("[SendBootstrapper] init..");
        }

        public void Start()
        {
            _scheduler.Start();
            LogHelper.Info("[SendBootstrapper] 启动完成..");
        }

        public void Stop()
        {
            _scheduler.Shutdown();
        }
    }
启动程序
 public  abstract class BaseJob:IJob
    {
       
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                LogHelper.Info("[{0}]Job excuting.LAST:{1}.JOB名称:{2}",
                    context.JobDetail.JobType.Name,
                    context.PreviousFireTimeUtc,
                    context.JobDetail.Description);
                var ts = PerformanceHelper.ExecuteWatch(Execute);

                LogHelper.Info("[{0}]Job excuted succ.运行时间:{1}. JOB名称:{2},预计下次执行时间:{3}(+8H),执行耗时:{4}",
                    context.JobDetail.JobType.Name,
                    context.JobRunTime,
                    context.JobDetail.Description,
                    context.NextFireTimeUtc,
                    ts
                );
            }
            catch (Exception ex)
            {
                LogHelper.Error("[{0}]Job excuted fault error.LAST:{1}. ERROR:{2},{3},{4}InnerException:{5},{6}",
                    context.JobDetail.JobType.Name,
                    context.PreviousFireTimeUtc,
                    ex.Message,
                    ex.StackTrace,
                    Environment.NewLine,
                    ex.InnerException != null ? ex.InnerException.Message : string.Empty,
                    ex.InnerException != null ? ex.InnerException.StackTrace : string.Empty);
            }
        }
        public abstract void Execute();
    }


  [DisallowConcurrentExecution]
    public class SendJob : BaseJob
    {
        public override void Execute()
        {
            DateTime now = DateTime.Now;
          
            DateTime endTime = Convert.ToDateTime("2018/10/18 19:00:00");
            DateTime beginTime = Convert.ToDateTime("2018/10/18 12:00:00");

            var instanceHeat = InstanceHelper<GpsDataMongoHeatStorage>.GetInstance();

      
            
            List<string> strList = new List<string>() { "018080100087" };

            var list = new List<GpsData>();
            foreach (var key in strList)
            {
               var keyList = instanceHeat.GetGpsData(key, beginTime, endTime);
                list.AddRange(keyList);
            }
            if (list.Count > 0)
            {
                //推送告警到平台
                EngineContext.Send(MessageType.LocationGps, list);
                LogHelper.Debug("推送数据条数:" + list.Count());
                return;
            }
        }
    }
Job类
<?xml version="1.0" encoding="UTF-8"?>

<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 version="2.0">

  <processing-directives>
    <overwrite-existing-data>true</overwrite-existing-data>
  </processing-directives>

  <schedule>

    <job>
      <name>SendJob</name>
      <group>jobGroup_SendJob</group>
      <description>Gps数据推送</description>
      <job-type>PushGpsDataTest.SendJob, PushGpsDataTest</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>
    <trigger>
      <cron>
        <name>SendJobTrigger</name>
        <group>jobGroup_SendJob</group>
        <job-name>SendJob</job-name>
        <job-group>jobGroup_SendJob</job-group>
        <cron-expression>*/30 * * * * ?</cron-expression>
      </cron>
    </trigger>
    
  </schedule>

</job-scheduling-data>
quartz_job.xml

 

posted on 2018-03-06 10:07  莫伊筱筱  阅读(310)  评论(0)    收藏  举报