quartz与spring boot-最简模式
多年前使用过quartz,今天又需要再用,而且是在spring boot框架下。很神奇,spring也是十年前用过的。
这里仅记录下完成的最快速和简单的操作,高级的使用以后有空弄明白了再写:
1、增加maven引用
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
2、编写任务代码:按自己要求编写类即可,每个任务做好标注@Scheduled(...)
package com.my.task; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component @Configurable @EnableScheduling public class HappyBirthday { /** * 使用spring 内置slf4j日志对象 */ private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 30秒间隔启动一次任务 */ @Scheduled(fixedRate = 1000 * 30) public void reportCurrentTime(){ logger.info ("Scheduling Tasks Examples: The time is now " + dateFormat ().format (new Date ())); } /** * 每分钟启动一次任务 */ @Scheduled(cron = "0 */1 * * * * ") public void reportCurrentByCron(){ logger.info ("Scheduling Tasks Examples By Cron: The time is now " + dateFormat ().format (new Date())); } private SimpleDateFormat dateFormat(){ return new SimpleDateFormat ("HH:mm:ss"); } }
3、done