springboot系列11: 定时任务

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

 

1、pom配置

 

<?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、启动类启用定时

@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {

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

 

3、创建定时任务实现类

方式1:

@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:

@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、运行结果

[现在时间: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 @ 2022-01-13 19:27  IT6889  阅读(39)  评论(0编辑  收藏  举报