最近看了springboot 定时器的使用,的确非常的简单,看了很多的博客,没有给出如何停止定时器的办法,想了一个暂时解决的办法,伪停止。
这里是pom.xml 所需的包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
项目启动类上加上注解
@SpringBootApplication
@EnableScheduling//这个是开启定时任务的注解
//@MapperScan("com.hqk.biz.mapper")
public class BizApplication {
public static void main(String[] args) {
SpringApplication.run(BizApplication.class, args);
}
}
接下来是定时任务的处理,以及如何停止定时任务. 这里的解决方案是,在项目启动的时候,可以把定时任务的相关字段加载到redis里面,然后定时job每次运行时去 redis 查看当前job是否是运行状态,如需停止job,则修改job的状态同时更新redis,这个停止job,任务还在运行,但是没有处理任务,伪停止job吧
@Component
public class MyTestJob {
private int count=0;
StringRedisTemplate stringRedisTemplate;
//@Scheduled(fixedRate = 6000) 都是每6秒执行一次
@Scheduled(cron="*/6 * * * * ?")
private void process(){
// 这里从redis 里面获取相应定时任务对应的状态,是否运行
String state=stringRedisTemplate.opsForValue().get("xxxjob");
if(state=="00"){
//如果 当前是 00,则运行相关代码
System.out.println("定时job scheduler 正在运行: "+(count++));
} else {
System.out.println("定时job scheduler 停止运行");
}
}
}