springboot -- 自带定时器实现定时任务的开启关闭以及定时时间可以配置
- pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
2.配置文件application.yml
crontest:
cron1: 0/10 * * * * ?
cron2: 0/5 * * * * ?
3.读取配置文件类代码
package com.ygf.config;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
/**
* Created by Administrator on 2019/8/5.
*/
@Data
@Component
@ConfigurationProperties(prefix="crontest")
@EqualsAndHashCode(callSuper = false)
public class CronTestConfiguration {
private String cron1;
private String cron2;
}
4.在启动类上配置@EnableScheduling 开启定时任务
- controller类:配置启停定时任务
@Slf4j
@RestController
@Api(description = "定时任务")
@RequestMapping("/quartz/task")
public class DynamicTaskController {
@Autowired
private CronTestConfiguration cronTestConfiguration;
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture future1;
@GetMapping("/startCron1")
public String startCron1() {
/**
* ThreadPoolTaskScheduler:线程池任务调度类,能够开启线程池进行任务调度。
* ThreadPoolTaskScheduler.schedule()方法会创建一个定时计划ScheduledFuture,在这个方法需要添加两个参数,
* Runnable(线程接口类) 和CronTrigger(定时任务触发器)
* YouXinConfiguration:自定义读取yml文件中数据的类,通过该类读取yml文件中cron时间表达式,从而可以达到定时时间可配置的效果。
* MyRunnable1与MyRunnable2类:这两个类都是实现了Runnable接口,重写了run方法,定时任务的逻辑代码就是在其中实现。
*/
future1 = threadPoolTaskScheduler.schedule(new MyRunnable1(), new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
return new CronTrigger(cronTestConfiguration.getCron2()).nextExecutionTime(triggerContext);
}
});
System.out.println("DynamicTask.startCron1()");
return "success";
}
@GetMapping("/stopCron1")
@ApiOperation("关闭定时任务1")
public String stopCron1() {
if (future1 != null) {
future1.cancel(true);
}
System.out.println("DynamicTask.stopCron1()");
return "success";
}
}
6.定时任务的业务执行类型 MyRunnable1.java
public class MyRunnable1 implements Runnable{
@Override
public void run() {
System.out.println("first DynamicTask,"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
7.在浏览器中调用 启停的url
http://localhost:8080/quartz/task/stopCron1 #停止
http://localhost:8080/quartz/task/startCron1 #启动定时任务
8.日志打印
DynamicTask.startCron1()
first DynamicTask,2019-08-05 10:35:00
first DynamicTask,2019-08-05 10:35:05
first DynamicTask,2019-08-05 10:35:10
first DynamicTask,2019-08-05 10:35:15
second before
DynamicTask.stopCron1()