论SpringBoot集成quartz的两种简单方式

一、第一种(配置类+任务类):

配置类如下:

@Slf4j
@Configuration
public class QuartzConfig  {

    /**
     * 统计日志
     */
    @Bean
    public JobDetail statsLogJobJobDetail() {
        return JobBuilder.newJob(StatsLogTask.class)
                .withIdentity(StatsLogTask.TASK_IDENTITY)
                .storeDurably().build();
    }

    @Bean
    public Trigger statsLogJobTrigger() {
        // 每天0点执行一次
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 0 * * ?");
        return TriggerBuilder.newTrigger()
                .forJob(statsLogJobJobDetail())
                .withIdentity(StatsLogTask.TASK_IDENTITY)
                .withSchedule(cronScheduleBuilder)
                .build();
    }

任务类如下:

@Slf4j
@Component
public class StatsLogTask extends QuartzJobBean {

    static final String TASK_IDENTITY = "StatsLogTask";
    
    @Override
    protected void executeInternal(@NonNull JobExecutionContext jobExecutionContext) {
        doPvUvStatistics();
    }

    /**
     *业务方法
     */
    private void doPvUvStatistics() {
        dosomething...
    }
}

二、第二种(任务类):

任务类如下:

@Slf4j
@Component("favoritesTask")
public class FavoritesTask implements SchedulingConfigurer, Ordered {

	//获取配置类,此处可以获取cron表达式即可,读者可自己想办法解决
    @Resource
    private QuartzPropertiesUntil quartzPropertiesUntil;
    
    @Resource
    private IWeeklyFavoritesService iWeeklyFavoritesService
    
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Runnable runnable = () -> {
            log.info("FavoritesTask-------- {}", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            //业务方法
            iWeeklyFavoritesService.transFavoritesFromRedis2Db();
        };

        Trigger trigger = triggerContext -> {
            CronTrigger cronTrigger = new CronTrigger(quartzPropertiesUntil.getFavoritesJobCron());
            return cronTrigger.nextExecutionTime(triggerContext);
        };
        scheduledTaskRegistrar.addTriggerTask(runnable, trigger);

    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}

此方法可以很好的跟apollo配置结合,实现不重启服务器的情况下变更cron表达式,达到灵活控制业务需求的目的。(以上两种方式,前提是导入spring-boot-starter-quartz依赖,并在启动类加@EnableScheduling注解才能实现),下一篇文章,关于如何实现apollo中quartz的动态配置

posted @ 2020-03-04 10:45  ${简简单单}  阅读(518)  评论(0编辑  收藏  举报