springboot系列11: 定时任务

在开发中,我们经常会用到定时任务来处理一些补处理的内容,springboot框架已经帮我们实现了,只需要添加相应的注解就可以直接使用。

 

1、pom配置

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-parent</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
 
    <artifactId>springboot-scheduling</artifactId>
 
    <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>
    </dependencies>
</project>

2、启动类启用定时

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SchedulingApplication.class, args);
    }
}

 

3、创建定时任务实现类

方式1:

1
2
3
4
5
6
7
8
9
10
@Component
public class SchedulerTask {
 
    private int count=0;
 
    @Scheduled(cron="*/6 * * * * ?")
    private void process(){
        System.out.println("[现在时间:"+ new SimpleDateFormat("HH:mm:ss").format(new Date()) +"] this is task1 runing:"+(count++));
    }
}

 

方式2:

1
2
3
4
5
6
7
8
9
@Component
public class Scheduler2Task {
    private int count=0;
 
    @Scheduled(fixedRate = 6000)
    public void process() {
        System.out.println("[现在时间:"+ new SimpleDateFormat("HH:mm:ss").format(new Date()) +"] this is task2 runing:"+(count++));
    }
}

 

4、运行结果

1
2
3
4
5
6
7
8
9
10
11
12
[现在时间:09:42:06] this is task1 runing:0
[现在时间:09:42:09] this is task2 runing:1
[现在时间:09:42:12] this is task1 runing:1
[现在时间:09:42:15] this is task2 runing:2
[现在时间:09:42:18] this is task1 runing:2
[现在时间:09:42:21] this is task2 runing:3
[现在时间:09:42:24] this is task1 runing:3
[现在时间:09:42:27] this is task2 runing:4
[现在时间:09:42:30] this is task1 runing:4
[现在时间:09:42:33] this is task2 runing:5
[现在时间:09:42:36] this is task1 runing:5
[现在时间:09:42:39] this is task2 runing:6

 

5、参数说明

@Scheduled 可以接受两种定时设置,一种常用cron表达式:cron="*/6 * * * * ?",另种 fixedRate = 6000, 两种都表示每隔6秒执行一次。

 

fixedRate 说明

@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行

@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行

@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按 fixedRate 的规则每6秒执行一次

    •  

 

posted @   IT6889  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示