欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringSchedule 定时任务框架使用步骤(基于SpringBoot)

程序员文章站 2022-06-28 16:21:39
在启动类上加上 @EnableScheduling注解,开启定时任务package com.lianxi;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootA...

在启动类上加上 @EnableScheduling注解,开启定时任务

package com.lianxi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling //开启定时任务
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class,args);
    }
}

在需要的方法上用 @Scheduled注解

注意:必须是交给Spring容器的类,才可以使用!!!
cron 表达式只能写6个,顺序:秒 分 时 日 月 周
在cron表达式中必须出现且只能出现1次,用在日域周域

作用域是@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})

我这个是每三秒执行一次

package com.lianxi.schedule.service;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ScheduleService {
    //用于计数
    private Integer index =1;
    //秒 分 时 日 月 周
    @Scheduled(cron = "0/3 * * * * ?") //表达式只能写6位
    public  void texitSchedule(){
        //具体业务
       log.debug("定时任务测试:嘿嘿嘿"+index);
       index++;
    }
}

配置文件以及依赖导入

配置文件:

默认情况下,定时任务的线程池大小只有1,当任务较多执行频繁时,会出现阻塞等待的情况,任务调度器就会出现时间漂移,任务执行时间将不确定

我们为了避免这样的情况发生,可以配置自定义线程池的大小

server:
  port: 8091

logging:
  level:
    com.lianxi: debug
# 默认情况下,定时任务的线程池大小只有1,当任务较多执行频繁时,会出现阻塞等待的情况,任务调度器就会出现时间漂移,任务执行时间将不确定
spring:
  task:
    scheduling:
      pool:
        size: 10  # 为了避免这样的情况发生,我们需要自定义线程池的大小

依赖导入:

我的SpringBoot版本是:2.1.3.RELEASE

因为 SpringSchedule 是Spring封装的,并且是自带的,它在 spring-context-5.1.5.RELEASE.jar里,所有我们导入SpringWeb就自动导入基本依赖

	<!--        SpringBoot依赖以及版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>
    
    <dependencies>
        <!--        Springweb启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

希望这篇文章,对你有所帮助

本文地址:https://blog.csdn.net/weixin_44257023/article/details/112219550