Quartz定时任务
Quartz简介
quartz是一个由java编写的任务调度库,由OpenSymphony组织开源出来。绝大多数公司都会用到任务调度这个功能, 比如公司需要定期执行任务调度生成报表, 或者比如博客什么的定时更新之类的,都可以靠Quartz来完成。
Quartz的基本组成部分:
-
调度器:Scheduler
-
任务:JobDetail
-
触发器:Trigger
案例:
1.添加Quartz依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
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里的访问量持久化方法 } }
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(); } }