scheduled会在上次任务执行完才会执行下次任务
在使用spring的scheduled定时任务
担心同一任务,
第一次开始未执行完就执行第二次任务,所以给加了synchronized,
但是后面经过测试scheduled定时任务会在上次任务结束时再执行第二次任务,
如果第二次任务堵在哪里了,时间会顺延
package xyz.hashdog.job;
import lombok.allargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
/**
* @author th
* @description: 定时任务测试
* @projectname hashdog-ds
* @date 2020/2/1223:07
*/
@component
@slf4j
@allargsconstructor
public class testcrontab {
private static final object key = new object();
private static boolean taskflag = false;
@scheduled(cron = "*/5 * * * * ?")
public void pushcancel() {
system.out.println("进来了");
synchronized (key) {
if (testcrontab.taskflag) {
system.out.println("测试调度已经启动");
log.warn("测试调度已经启动");
return;
}
testcrontab.taskflag = true;
}
try {
for (int i =0;i<=10;i++){
system.out.println("执行:"+i);
thread.sleep(2000);
}
} catch (exception e) {
log.error("测试调度执行出错", e);
}
testcrontab.taskflag = false;
log.warn("测试调度执行完成");
}
}注释掉synchronized
执行效果一样,并没有线程安全问题
package xyz.hashdog.job;
import lombok.allargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
/**
* @author th
* @description: 定时任务测试
* @projectname hashdog-ds
* @date 2020/2/1223:07
*/
@component
@slf4j
@allargsconstructor
public class testcrontab {
private static final object key = new object();
private static boolean taskflag = false;
@scheduled(cron = "*/5 * * * * ?")
public void pushcancel() throws interruptedexception {
system.out.println("进来了");
// synchronized (key) {
// if (testcrontab.taskflag) {
// system.out.println("测试调度已经启动");
// log.warn("测试调度已经启动");
// return;
// }
// testcrontab.taskflag = true;
// }
//
// try {
for (int i =0;i<=10;i++){
system.out.println("执行:"+i);
thread.sleep(2000);
}
// } catch (exception e) {
// log.error("测试调度执行出错", e);
// }
//
// testcrontab.taskflag = false;
log.warn("测试调度执行完成");
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论