SpringBoot2.0集成定时任务(一)
一、实现Quartz之前先介绍一下其他的实现方式。
1、使用Timer创建简单的定时任务
注:需要对定时任务的执行体进行异常捕捉,否则该任务会中断执行。见标红处代码。
List<String> lis = Arrays.asList("{\"s1\":\"1000\",\"s2\":\"2000\",\"s3\":\"TimerTask1\"}","{\"s1\":\"1000\",\"s2\":\"4000\",\"s3\":\"TimerTask2\"}");
lis.forEach(obj -> {
JSONObject str = JSON.parseObject(obj);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("TimerTask run :"+ str.getString("s3")+"===========" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
if(str.getString("s3").endsWith("2")){
System.out.println(1/0);
}
}
},Long.parseLong(str.getString("s1")),Long.parseLong(str.getString("s2")));//延时1s,之后每隔5s运行一次
});
有两点问题需要注意:
1.
2.同一个1.
scheduleAtFixedRate和schedule的区别:scheduleAtFixedRate会尽量减少漏掉调度的情况,如果前一次执行时间过长,导致一个或几个任务漏掉了,那么会补回来,而schedule过去的不会补,直接加上间隔时间执行下一次任务。Timer下添加多个TimerTask,如果其中一个没有捕获抛出的异常,则全部任务都会终止运行。但是多个Timer是互不影响。
2、使用ScheduledThreadPoolExecutor创建定时任务。
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5);
executorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println("ScheduledThreadPoolExecutor1 run:"+now);
}
},1,2, TimeUnit.SECONDS);
注:scheduleWithFixedDelay跟schedule类似,而scheduleAtFixedRate与scheduleAtFixedRate一样会尽量减少漏掉调度的情况。
二、springboot项目使用Scheduled。
- 启动类添加
@EnableScheduling - 定时任务方法上添加
@Scheduled
@Component
public class SpringScheduled {
@Scheduled(cron = "1/5 * * * * ?")
public void testScheduled(){
System.out.println("springScheduled run:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
}
}

浙公网安备 33010602011771号