Spring Boot如何创建一个定时任务呢?

乔欣 SpringBoot 发布时间:2023-02-13 11:41:18 阅读数:14766 1
下文笔者讲述SpringBoot中创建定时任务的方法分享,如下所示

Springboot创建定时任务的实现思路

实现思路:
    1.引入jar包
	2.启动类上加入@EnableScheduling注解,开启定时任务
	3.使用@Scheduled注解定义一个任务即可
例:

pom包配置

pom.xml中引入以下依赖
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

启动类启用定时

 启动类上
  加上@EnableScheduling注解
  即可开启定时
@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

创建定时任务实现类

定时任务1

@Component
public class SchedulerTask {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    private void process(){
        System.out.println("this is scheduler task runing  "+(count++));
    }

}

定时任务2

@Component
public class Scheduler2Task {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }

}
运行以上代码,将输出以下信息
this is scheduler task runing  0
现在时间:11:50:17
this is scheduler task runing  1
现在时间:11:50:23
this is scheduler task runing  2
现在时间:11:50:29
this is scheduler task runing  3
现在时间:11:50:35

参数说明

@Scheduled 参数:
   可以接受两种定时的设置
   方式1:
      常用的cron="*/7 * * * * ?"
   方式2:
     使用fixedRate = 7000
   //两种都表示每隔七秒打印一下

fixedRate参数说明
@Scheduled(fixedRate = 7000) :上一次开始执行时间点之后7秒再执行
@Scheduled(fixedDelay = 7000) :上一次执行完毕时间点之后7秒再执行
@Scheduled(initialDelay=1000, fixedRate=7000) :第一次延迟1秒后执行
    之后按fixedRate的规则每7秒执行一次
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202302/5777.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者