springboot系列11: 定时任务


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

1、pom配置

<?xml version="1.0" encoding="UTF-8"?>

    
        springboot-parent
        com.example
        0.0.1-SNAPSHOT
    
    4.0.0

    springboot-scheduling

    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
     

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秒执行一次