SpringBoot中实现定时任务(Quartz)

一、使用Spring Task

Spring 3.0以后自带了 task 调度工具,使用比 Quartz简单方便,使用 @Scheduled 注解。

1、创建一个 SpringBoot项目,引入spring-boot-starter-web依赖。

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

  1. 在启动类上添加 @EnableScheduling 注解,表示开启定时任务。
@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(QuartzApplication.class, args);
    }
 
}
  1. 了解 @Scheduled 注解

在方法上使用 @Scheduled 注解表示开启一个定时任务:下面参数单位都是毫秒

  • fixedRate:表示按一定频率来执行定时任务,具体是指两次任务的开始时间间隔,即第二次任务开始时,第一次任务可能还没结束。
  • fixedDelay:表示按一定时间间隔来执行定时任务,具体是指本次任务结束到下次任务开始之间的时间间隔。该属性还可以配合initialDelay使用, 定义该任务延迟执行时间。
  • initialDelay:表示首次任务启动的延迟时间。与fixedDelay配合使用。
  • cron:通过 cron 表达式来配置任务执行时间,cron 表达式格式为:[秒] [分] [小时] [日] [月] [周] [年]

2、单线程执行任务

使用同一个线程中串行执行,如果只有一个定时任务,这样做肯定没问题,当定时任务增多,如果一个任务卡死,会导致其他任务也无法执行。

  1. 创建一个类,配置定时任务
@Component
public class Task1 {
 
    @Scheduled(fixedRate = 2000)
    public void fixedRateTask() {
        System.out.println("fixedRateTask定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
    }
 
    @Scheduled(fixedDelay = 2000)
    public void fixedDelayTask1() {
        System.out.println("fixedDelayTask1111定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
    }
 
    @Scheduled(initialDelay = 2000,fixedDelay = 2000)
    public void initialDelayTask2() throws InterruptedException {
        System.out.println("initialDelayTask2222定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
        TimeUnit.SECONDS.sleep(15);
    }
 
    @Scheduled(cron = "0/5 * * * * ?")
    public void cron() {
        System.out.println("cron定时任务开始 : " + LocalDateTime.now().toLocalTime() + ",线程:" + Thread.currentThread().getName());
    }
}

 2.启动项目,定时任务就开始工作了

  • 可以看到使用的是同一个线程,并出现了任务阻塞的情况。

image.png

3、多线程执行任务

Spring Task 默认是单线程的,想要改成多线程,

给Spring Task提供一个多线程的TaskScheduler,Spring已经有默认实现。

  1. 方式一

创建配置类,@EnableAsync注解:表示开启异步事件的支持

@Configuration
@EnableAsync // 开启异步事件的支持
public class AsyncTaskConfig {
 
    private int corePoolSize = 10;
    private int maxPoolSize = 200;
    private int queueCa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Mervin_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值