SpringBoot学习记录----如何使用Scheduled调度任务

 

为了学习SpringBoot,将平时学到的记录下来。本文将详细讲述如何使用注解来完成一个定时执行功能。

1、准备工作

首先,创建一个maven项目,如何创建maven项目请参考:https://blog.csdn.net/chenzz2560/article/details/83270232。在创建完maven项目后,在pom.xml中导入SpringBoot运行需要的依赖包。



    4.0.0

    czz.study
    scheduled
    0.1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.jayway.jsonpath
            json-path
            test
        
    

    
        1.8
    


    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

2、创建要运行的程序

创建一个class类,里面包含了你要定时运行的方法。@Component 注解将这个类声明为一个Bean对象,交给Spring进行管理,@Scheduled 注解声明了这个方法是一个定时方法,cron属性表明了这个方法运行的规则,test1表明每10秒运行一次,test2表明每9秒运行一次,这个可以通过cron在线生成。

package czz.study.schdule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestSchdule {

    @Scheduled(cron = "0/10 * * * * ? ")
    private void test1() {

        System.out.println("定时器1定时运行");
    }

    @Scheduled(cron = "0/9 * * * * ? ")
    private void test2() {

        System.out.println("定时器2定时运行");
    }
}

3、运行程序

创建一个启动类,@SpringBootApplication 功能相当于@Configuration,@EnableAutoConfiguration,@ComponentScan这三个注解,SpringApplication.run(Main.class, args)这行代码用来声明项目入口,没有这行代码,使用的Spring注解都会失效(等于没有注解)。@EnableScheduling用来声明 @Scheduled注解可用,只有添加了@EnableScheduling,程序才会定时运行被@Scheduled注解的方法。

package czz.study;

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

@SpringBootApplication
@EnableScheduling
public class Main {

    public static void main(String[] args) {

        SpringApplication.run(Main.class, args);
    }
}

4、运行结果

从结果可以看出,test1从0秒开始,每10秒运行一次,test2从0秒开始,每9秒运行一次。

SpringBoot学习记录----如何使用Scheduled调度任务_第1张图片

 总结:除了使用cron表达式,Schedule还可以使用fixedRate(每隔多少毫秒执行),fixedDelay(每次执行任务之后间隔多久毫秒再次执行该任务)等方法来操控方法执行的频率。

你可能感兴趣的:(SpringBoot学习记录)