C# .net Quartz.net 动态添加修改时间

一:使用原因,不使用windows服务。quartz.net框架使用方便

二:使用方法如下

  1.Nuget下载,博主用的是 Quartz 2.6.1版本

  2.需要QuartzManage帮助类放在项目里,如下:

public class QuartzManage
    {
        private static ISchedulerFactory sf = new StdSchedulerFactory();    //创建一个调度器工厂
        private static String JOB_GROUP_NAME = "group";                        
        private static String TRIGGER_GROUP_NAME = "trigger";
        private static IScheduler sched;            //创建一个调度器    

        public static void StartJob(string jobName, Type jobType, string time) 
        {
            sched = sf.GetScheduler();              //工厂生成一个调度器 

            JobDetailImpl jobDetail = new JobDetailImpl();      //新建一个任务 
            jobDetail.Name = jobName;
            jobDetail.Group = JOB_GROUP_NAME;
            jobDetail.JobType = jobType;

            CronTriggerImpl trigger = new 
          CronTriggerImpl(jobName, TRIGGER_GROUP_NAME);//新建一个触发器 trigger.CronExpressionString = time; sched.ScheduleJob(jobDetail, trigger); //将任务与触发器添加到调度器中 if (!sched.IsShutdown) { sched.Start(); } } /** * 从Scheduler 移除当前的Job,修改Trigger * * @param jobDetail * @param time * @throws SchedulerException * @throws ParseException */ public static void ModifyJobTime(ITrigger trigger, IJobDetail jobDetail, string time) { sched = sf.GetScheduler(); if (trigger != null) { CronTriggerImpl ct = (CronTriggerImpl)trigger; // 移除当前进程的Job sched.DeleteJob(jobDetail.Key); // 修改Trigger ct.CronExpressionString = time; // 重新调度jobDetail sched.ScheduleJob(jobDetail, ct); } } public static void ShutDownJob() { if (sched != null && !sched.IsShutdown) { sched.Shutdown(); } } }

 3.   执行内容。必须继承IJob

 public class TimeJob : IJob    
        {
            public void Execute(IJobExecutionContext context)
            {
                System.IO.File.AppendAllText(@"c:\Quartz.txt", DateTime.Now + Environment.NewLine);
            }
        } 

4.执行Cron规则制定,可以动态添加修改Quartz执行规则(触发方式自己可以随场景而定)

  QuartzManage.StartJob("job1", typeof(TimeJob), "0/3 * * * * ?");  //三秒执行一次
  Thread.Sleep(20000);  
  QuartzManage.ShutDownJob();
  QuartzManage.StartJob("job1", typeof(TimeJob), "0/6 * * * * ?");  //六秒执行一次

 

posted @ 2019-03-18 16:24  超级驼鹿  阅读(1953)  评论(0编辑  收藏  举报
/*