Quartz定时任务

Quartz简介

quartz是一个由java编写的任务调度库,由OpenSymphony组织开源出来。绝大多数公司都会用到任务调度这个功能, 比如公司需要定期执行任务调度生成报表, 或者比如博客什么的定时更新之类的,都可以靠Quartz来完成。

Quartz的基本组成部分:

  • 调度器:Scheduler

  • 任务:JobDetail

  • 触发器:Trigger

案例:

把Redis中的博客点击量在凌晨0点时持久化进Mysql

1.添加Quartz依赖


    org.springframework.boot
    spring-boot-starter-quartz

2.创建一个任务

import com.cch.gofy.service.ArticleInfoService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

@Slf4j
public class PersistenceJob extends QuartzJobBean {

    @Autowired
    ArticleInfoService articleInfoService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("PersistenceJob---------"+new Date());
        articleInfoService.persistenceTraffic();//将redis里的访问量持久化方法
    }
}

3.创建Quartz配置类

import com.cch.gofy.util.PersistenceJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {

    String identity = "PersistenceTraffic";

    @Bean
    public JobDetail quartzJob(){
        return JobBuilder.newJob(PersistenceJob.class)
        .withIdentity(identity).
        storeDurably().build();
    }

    @Bean
    public Trigger quartzTrigger(){
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 0 * * ? "); //参数为Cron表达式,既让job任务执行的时间,这里是每天凌晨0点

        return TriggerBuilder.newTrigger().forJob(identity)
                .withIdentity(identity)
                .withSchedule(scheduleBuilder)
                .build();
    }

}

 我的个人博客 www.gofy.top

你可能感兴趣的:(Quartz定时任务)