Springboot中怎么利用@Scheduled实现定时任务
创始人
2024-12-24 09:25:34
0次

使用@Scheduled 可以很容易实现定时任务

spring boot的版本 2.1.6.RELEASE

package com.abc.demo.common;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.concurrent.TimeUnit;@EnableScheduling@Componentpublic class ScheduleSetting {  private final Logger logger = LoggerFactory.getLogger(Tasks.class);  @Scheduled(fixedRate = 10000, initialDelay = 2000)  public void scheduleRead() {    try {      long timeStamp = System.currentTimeMillis();      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      Thread thread = Thread.currentThread();      System.out.println("cron1任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());      long endStamp = System.currentTimeMillis();      try {        TimeUnit.SECONDS.sleep(20);      } catch (InterruptedException e) {        e.printStackTrace();      }      System.out.println("cron1任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));      System.out.println("++++++++++++++++++++++++");    } catch (Exception e) {      logger.error(e.getMessage());    }  }  @Scheduled(fixedRate = 5000, initialDelay = 1000)  public void scheduleConvert() {    try {      long timeStamp = System.currentTimeMillis();      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      Thread thread = Thread.currentThread();      System.out.println("cron2任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());      try {        TimeUnit.SECONDS.sleep(10);      } catch (InterruptedException e) {        e.printStackTrace();      }      long endStamp = System.currentTimeMillis();      System.out.println("cron2任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));      System.out.println("====================");    } catch (Exception e) {      logger.error(e.getMessage());    }  }}

运行输出内容为

cron2任务开始,start=2019-10-11 17:31:52, threadId=34, threadName=scheduling-1cron2任务正在运行的线程名称:scheduling-1 结束,start=2019-10-11 17:31:52,end=2019-10-11 17:32:02====================cron1任务开始,start=2019-10-11 17:32:02, threadId=34, threadName=scheduling-1cron1任务正在运行的线程名称:scheduling-1 结束,start=2019-10-11 17:32:02,end=2019-10-11 17:32:02++++++++++++++++++++++++cron2任务开始,start=2019-10-11 17:32:22, threadId=34, threadName=scheduling-1cron2任务正在运行的线程名称:scheduling-1 结束,start=2019-10-11 17:32:22,end=2019-10-11 17:32:32……

注:

  cron2执行完后才会执行cron1

原因:

  spring默认是以单线程执行任务调度

  spring的定时任务默认最大运行线程数为1,多个任务执行起来时间会有问题

1.配置线程池

在配置文件application.properties中添加

# 线程池大小spring.task.scheduling.pool.size=5# 线程名前缀spring.task.scheduling.thread-name-prefix=myScheduling-

输出内容变为

cron2任务开始,start=2019-10-11 17:34:48, threadId=34, threadName=myScheduling-1cron1任务开始,start=2019-10-11 17:34:49, threadId=35, threadName=myScheduling-2cron2任务正在运行的线程名称:myScheduling-1 结束,start=2019-10-11 17:34:48,end=2019-10-11 17:34:58====================cron2任务开始,start=2019-10-11 17:34:58, threadId=34, threadName=myScheduling-1cron2任务正在运行的线程名称:myScheduling-1 结束,start=2019-10-11 17:34:58,end=2019-10-11 17:35:08====================cron2任务开始,start=2019-10-11 17:35:08, threadId=57, threadName=myScheduling-3cron1任务正在运行的线程名称:myScheduling-2 结束,start=2019-10-11 17:34:49,end=2019-10-11 17:34:49……

注:

多线程下,cron1和cron2不用互相等待了,但是同一个任务还是需要等待的

2.并发

修改代码

package com.abc.demo.common;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.concurrent.TimeUnit;@EnableScheduling@Component@EnableAsyncpublic class ScheduleSetting {  private final Logger logger = LoggerFactory.getLogger(Tasks.class);  @Async  @Scheduled(fixedRate = 10000, initialDelay = 2000)  public void scheduleRead() {    try {      long timeStamp = System.currentTimeMillis();      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      Thread thread = Thread.currentThread();      System.out.println("cron1任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());      long endStamp = System.currentTimeMillis();      try {        TimeUnit.SECONDS.sleep(20);      } catch (InterruptedException e) {        e.printStackTrace();      }      System.out.println("cron1任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));      System.out.println("++++++++++++++++++++++++");    } catch (Exception e) {      logger.error(e.getMessage());    }  }  @Async  @Scheduled(fixedRate = 5000, initialDelay = 1000)  public void scheduleConvert() {    try {      long timeStamp = System.currentTimeMillis();      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      Thread thread = Thread.currentThread();      System.out.println("cron2任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());      try {        TimeUnit.SECONDS.sleep(10);      } catch (InterruptedException e) {        e.printStackTrace();      }      long endStamp = System.currentTimeMillis();      System.out.println("cron2任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));      System.out.println("====================");    } catch (Exception e) {      logger.error(e.getMessage());    }  }}

输出的内容

cron2任务开始,start=2019-10-11 17:39:53, threadId=57, threadName=task-1cron1任务开始,start=2019-10-11 17:39:54, threadId=59, threadName=task-2cron2任务开始,start=2019-10-11 17:39:58, threadId=61, threadName=task-3cron2任务开始,start=2019-10-11 17:40:03, threadId=63, threadName=task-4cron2任务正在运行的线程名称:task-1 结束,start=2019-10-11 17:39:53,end=2019-10-11 17:40:03====================cron1任务开始,start=2019-10-11 17:40:04, threadId=64, threadName=task-5cron2任务开始,start=2019-10-11 17:40:08, threadId=65, threadName=task-6cron2任务正在运行的线程名称:task-3 结束,start=2019-10-11 17:39:58,end=2019-10-11 17:40:08====================cron2任务开始,start=2019-10-11 17:40:13, threadId=66, threadName=task-7cron2任务正在运行的线程名称:task-4 结束,start=2019-10-11 17:40:03,end=2019-10-11 17:40:13====================cron1任务正在运行的线程名称:task-2 结束,start=2019-10-11 17:39:54,end=2019-10-11 17:39:54

说明: 

  @EnableAsync开启多线程    @Async标记其为一个异步任务    每个定时任务都是在通过不同的线程来处理,线程名的前缀成了task-    线程默认为10个

修改配置

spring.task.execution.thread-name-prefix=mytask-spring.task.execution.pool.core-size=5

重新运行的输出

cron2任务开始,start=2019-10-11 17:44:00, threadId=56, threadName=mytask-1cron1任务开始,start=2019-10-11 17:44:01, threadId=57, threadName=mytask-2cron2任务开始,start=2019-10-11 17:44:05, threadId=58, threadName=mytask-3cron2任务开始,start=2019-10-11 17:44:10, threadId=59, threadName=mytask-4cron2任务正在运行的线程名称:mytask-1 结束,start=2019-10-11 17:44:00,end=2019-10-11 17:44:10====================cron1任务开始,start=2019-10-11 17:44:11, threadId=60, threadName=mytask-5cron2任务正在运行的线程名称:mytask-3 结束,start=2019-10-11 17:44:05,end=2019-10-11 17:44:15====================cron2任务开始,start=2019-10-11 17:44:15, threadId=58, threadName=mytask-3cron2任务开始,start=2019-10-11 17:44:20, threadId=56, threadName=mytask-1cron2任务正在运行的线程名称:mytask-4 结束,start=2019-10-11 17:44:10,end=2019-10-11 17:44:20====================cron1任务正在运行的线程名称:mytask-2 结束,start=2019-10-11 17:44:01,end=2019-10-11 17:44:01

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...