Quartz源码解析(1)快速使用

2018-11-08  本文已影响0人  全都是泡沫啦

本章节使用Quartz的基于内存,非集群模式的任务调度StdScheduler讲解

  <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
      <version>2.2.1</version>
  </dependency>
import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.AbstractTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author paul
 * @description
 * @date 2018/11/8
 */
public class QuartzTest {

    //    <dependency>
    //        <groupId>org.quartz-scheduler</groupId>
    //        <artifactId>quartz</artifactId>
    //        <version>2.2.1</version>
    //    </dependency>
    public static void main(String[] args) throws SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobDetailImpl jobDetail = (JobDetailImpl) JobBuilder.newJob(JobRun.class).build();
        {
            jobDetail.setName("JobDetail-A1");
            jobDetail.setGroup("Job-Group-A");
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            jobDataMap.put("job-data-key", "job-data-value");
        }

        CronTrigger cronTrigger = TriggerBuilder.newTrigger().startNow()
                .withSchedule(
                        CronScheduleBuilder.cronSchedule("*/1 * * * * ?").withMisfireHandlingInstructionDoNothing()
                ).build();
        {
            cronTrigger.getJobDataMap().put("trigger-data-key", "trigger-data-value");
            ((AbstractTrigger) cronTrigger).setName("SimpleTrigger-A1");
            ((AbstractTrigger) cronTrigger).setGroup("Trigger-Group-A");

            SchedulerContext context = scheduler.getContext();
            context.put("context-data-key", "context-data-value");
        }
        scheduler.scheduleJob(jobDetail, cronTrigger);
        scheduler.start();

    }

    @PersistJobDataAfterExecution //是否要存储上一次运行的数据,只针对jobDetail.getJobDataMap()
    @DisallowConcurrentExecution  //不允许job对于在单trigger或者多trigger并发执行
    public static class JobRun implements Job {
        private static final Logger LOGGER = LoggerFactory.getLogger(JobRun.class);
        public static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
            LOGGER.info("run..." + Arrays.deepToString(jobDataMap.getKeys()));
            int i = ATOMIC_INTEGER.incrementAndGet();
            jobDataMap.put("key-" + i, "value-" + i);
        }
    }
}


上一篇下一篇

猜你喜欢

热点阅读