SpringBoot三种方式实现定时任务

SpringBoot三种方式实现定时任务
定时任务实现的三种方式:

Timer:这是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少。

ScheduledExecutorService:也jdk自带的一个类;是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。

Spring Task:Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多。

使用Timer

这个目前在项目中用的较少,直接贴demo代码。具体的介绍可以查看api

 
  1. public class TestTimer {

  2.     public static void main(String[] args) {

  3.         TimerTask timerTask = new TimerTask() {

  4.             @Override

  5.             public void run() {

  6.                 System.out.println("task  run:"+ new Date());

  7.             }

  8.         };

  9.         Timer timer = new Timer();

  10.         //安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次

  11.         timer.schedule(timerTask,10,3000);

  12.     }

  13. }

使用ScheduledExecutorService

该方法跟Timer类似,直接看demo:

 
  1. public class TestScheduledExecutorService {

  2.     public static void main(String[] args) {

  3.         ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

  4.         // 参数:1、任务体 2、首次执行的延时时间

  5.         //      3、任务执行间隔 4、间隔时间单位

  6.         service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+new Date()), 0, 3, TimeUnit.SECONDS);

  7.     }

  8. }

使用Spring Task

1,简单的定时任务
在SpringBoot项目中,我们可以很优雅的使用注解来实现定时任务,首先创建项目,导入依赖:

 
  1. <dependencies>

  2.   <dependency>

  3.     <groupId>org.springframework.boot</groupId>

  4.     <artifactId>spring-boot-starter-web</artifactId>

  5.   </dependency>

  6.   <dependency>

  7.     <groupId>org.springframework.boot</groupId>

  8.     <artifactId>spring-boot-starter</artifactId>

  9.   </dependency>

  10.   <dependency>

  11.     <groupId>org.projectlombok</groupId>

  12.     <artifactId>lombok</artifactId>

  13.     <optional>true</optional>

  14.   </dependency>

  15.   <dependency>

  16.     <groupId>org.springframework.boot</groupId>

  17.     <artifactId>spring-boot-starter-test</artifactId>

  18.     <scope>test</scope>

  19.   </dependency>

  20. </dependencies>

创建任务类:

 
  1. @Slf4j

  2. @Component

  3. public class ScheduledService {

  4.     @Scheduled(cron = "0/5 * * * * *")

  5.     public void scheduled(){

  6.         log.info("=====>>>>>使用cron  {}",System.currentTimeMillis());

  7.     }

  8.     @Scheduled(fixedRate = 5000)

  9.     public void scheduled1() {

  10.         log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());

  11.     }

  12.     @Scheduled(fixedDelay = 5000)

  13.     public void scheduled2() {

  14.         log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());

  15.     }

  16. }

在主类上使用@EnableScheduling注解开启对定时任务的支持,然后启动项目
可以看到三个定时任务都已经执行,并且使同一个线程中串行执行,如果只有一个定时任务,这样做肯定没问题,当定时任务增多,如果一个任务卡死,会导致其他任务也无法执行。

2,多线程执行
在传统的Spring项目中,我们可以在xml配置文件添加task的配置,而在SpringBoot项目中一般使用config配置类的方式添加配置,所以新建一个AsyncConfig类

 
  1. @Configuration

  2. @EnableAsync

  3. public class AsyncConfig {

  4.      /*

  5.     此处成员变量应该使用@Value从配置中读取

  6.      */

  7.     private int corePoolSize = 10;

  8.     private int maxPoolSize = 200;

  9.     private int queueCapacity = 10;

  10.     @Bean

  11.     public Executor taskExecutor() {

  12.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

  13.         executor.setCorePoolSize(corePoolSize);

  14.         executor.setMaxPoolSize(maxPoolSize);

  15.         executor.setQueueCapacity(queueCapacity);

  16.         executor.initialize();

  17.         return executor;

  18.     }

  19. }

@Configuration:表明该类是一个配置类
@EnableAsync:开启异步事件的支持

然后在定时任务的类或者方法上添加@Async 。最后重启项目,每一个任务都是在不同的线程中。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值