springboot集成quartz框架的基本步骤-爱代码爱编程
- 引入依赖
<!-- pom 文件 Spring Quartz 依赖 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
2) 我们需要使用注解@Configuration 来定义一个配置类,代码如下:
@Configuration //相当于 xml 文件中的<beans>
public class ConfigMyTools {
/**
* 格式化当前日期
* @return
*/
@Bean("dateFormat")
public SimpleDateFormat dateFormat(){
return new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
}
}
3) 为了方便我们看清楚任务调度的次数,我们声明一个辅助类,代码如下:
@Component("myTask")
public class MyTask {
private int count = 0;
public void say(){
System.out.println("大家好,我是 springboot 任务调度=>"+count++);
}
}
4) 接下创建一个任务调度的类,代码如下:
package com.ysd.springboot.quartz;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
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 com.ysd.springboot.config.MyTask;
@Component
@EnableScheduling //启动定时任务
public class SimpleTask {
@Autowired
private MyTask myTask;
@Resource
private SimpleDateFormat dateFormat;
@Scheduled(fixedRate = 1000 * 3) //每隔三秒
public void reportCurrentTime(){
myTask.say();//执行任务方法
System.out.println ("每隔 3 秒任务调度一次 现在时间 " + dateFormat.format (new Date ()));
}
//每隔 5 秒(cron 表达式,六个*【*/5 算一个,?算一个】,从左到右分别为秒分时天月年)
@Scheduled(cron = "*/5 * * * * ? ")
public void reportCurrentByCron(){
System.out.println ("每隔 5 秒任务调度一次 Scheduling Tasks Examples By Cron: The time is now " +
dateFormat.format (new Date ()));
}
}
5) 最后定义主模块启动类,启动测试即可。在控制台的结果如下图: