spring boot集成quartz
2020-04-29 本文已影响0人
刘小刀tina
1 pom.xml
<!--mybatis的依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--spring boot集成quartz依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!--mysql依赖的包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
<scope>runtime</scope>
</dependency>
============================================================
#配置mysql数据源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://152.136.27.48:3306/d_demo?characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
username: root
password: 123456
2 代码
@Configuration
@EnableScheduling //开启任务调度
@Slf4j
public class SimpleJob {
@Scheduled(cron = "0/2 * * * * ?")
public void run(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = dateFormat.format(new Date());
// log.error("当前时间为"+dateTime);
System.err.println("SimpleJob当前时间为"+dateTime);
}
}
//创建一个类
@Configuration
@EnableScheduling
@Slf4j
class ComplexJob implements SchedulingConfigurer{
//创建一个dao层的对象并注入到容器中
@Mapper
public interface CronMapper{
@Select("select cron from t_cron limit 0,1 ")
String getCron();
}
@Autowired
@SuppressWarnings("all")
private CronMapper cronMapper;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
/**
* 第一种写法
*/
scheduledTaskRegistrar.addTriggerTask(
new Runnable() {
@Override
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = dateFormat.format(new Date());
log.info("ComplexJob当前时间为" + dateTime);
}
},
new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
String cron = cronMapper.getCron();
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
}
);
/**
* 第二种写法
*/
scheduledTaskRegistrar.addTriggerTask(
()->{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = dateFormat.format(new Date());
log.info("当前时间为" + dateTime);
},
triggerContext -> {
String cron = cronMapper.getCron();
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}