类存储job信息

public class JobInfo {//省略setter getter
    String jobName;
    String jobGroup;
    Class<? extends Job> jobClass;
    JobDataMap dataMap;
    public JobInfo() {}
    public JobInfo(String jobName, String jobGroup, Class<? extends Job> jobClass, JobDataMap dataMap) {
        this.jobName = jobName;
        this.jobGroup = jobGroup;
        this.jobClass = jobClass;
        this.dataMap = dataMap;
    }
}

实现类,继承Job接口

public class HelloJob implements Job {
    private static final Logger logger = Logger.getLogger(HelloJob.class);
    public HelloJob() {}
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.error("*****************job start*****************");
        JobKey jobKey = jobExecutionContext.getJobDetail().getKey();
        // JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
        String name = dataMap.getString("name");
        logger.info("*****************good job*****************");
        logger.info("*****************" + jobKey + "--" + name + "*****************");
        logger.error("*****************job end*****************");
    }
}

测试,三种任务(Once、Repeat、Cron)

public class QuartzTest {
    public static void main(String[] args) {
        JobInfo jobInfo = new JobInfo();
        jobInfo.setJobClass(HelloJob.class);
        jobInfo.setJobName("myJob");
        jobInfo.setJobGroup("myGroup");
        Map map = new HashMap();
        map.put("name", "wxy");
        JobDataMap jobDataMap = new JobDataMap(map);
        jobInfo.setDataMap(jobDataMap);
        try {
            // Grab the Scheduler instance from the Factory
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            // and start it off
            scheduler.start();

            JobDetail job = createJob(jobInfo);
            // Trigger trigger = createSimpleOrRepeatTrigger(jobInfo);
            String cron = "0/10 * * * * ? ";
            Trigger trigger = createCronTrigger(jobInfo, cron);

            scheduler.scheduleJob(job, trigger);

            TimeUnit.MILLISECONDS.sleep(10 * 60 * 1000);
            scheduler.shutdown();

        } catch (SchedulerException se) {
            se.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static JobDetail createJob(JobInfo jobInfo) {
        JobDetail job = newJob(jobInfo.getJobClass()).withIdentity(jobInfo.getJobName(), jobInfo.getJobGroup())
                .usingJobData(jobInfo.getDataMap())
                .build();
        return job;
    }

    private static Trigger createSimpleOrRepeatTrigger(JobInfo jobInfo) {
        Trigger trigger = newTrigger().withIdentity(jobInfo.getJobName() + "_trg", jobInfo.getJobGroup())
                .startNow()
                // .startAt(futureDate(5, DateBuilder.IntervalUnit.MINUTE))
                // .startAt(dateOf(10, 37, 0))
                // .endAt(dateOf(11, 0, 0))
                .withSchedule(
                        simpleSchedule()
                                .withRepeatCount(1)
                                .withIntervalInSeconds(10)
                        // .repeatForever()
                )
                .build();
        return trigger;
    }

    private static Trigger createCronTrigger(JobInfo jobInfo, String cron) {
        Trigger trigger = newTrigger().withIdentity(jobInfo.getJobName() + "_trg", jobInfo.getJobGroup())
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(cron).inTimeZone(TimeZone.getDefault())
                )
                .build();
        return trigger;
    }

}

  

springboot使用定时器,定时器数据存在表中

@Configuration
public class CompleteScheduleConfig implements SchedulingConfigurer {
    @Autowired
    CronMapper cronMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                () -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
                triggerContext -> {
                    String cron = cronMapper.getCron();
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }

    @Mapper
    public interface CronMapper {
        @Select("select cron from cron limit 1")
        String getCron();
    }
}
View Code

表中数据如下:

cron_id   cron
1 0/10 * * * * ?

 

 

 

 

posted on 2019-11-07 17:32  MC伍  阅读(196)  评论(0编辑  收藏  举报