SpringBoot 定时任务的使用

SpringBoot自带了定时任务的功能,不需要额外添加依赖。

 

1、在引导类上加@EnableScheduling

@SpringBootApplication
@EnableScheduling  //启用定时任务
public class DemoApplication {

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

}

2、在要定时执行的方法上加@Scheduled

这里我们随便写一个类,随便写一个方法

@Component
public class Test {

    @Scheduled(cron = "0/5 * * * * *")   //定时执行,秒分时日月年
    public void out(){
        System.out.println("ok");
    }

}

@Scheduled将一方法标识为定时方法。

cron指定时间间隔,6部分:从前往后依次为 秒分时日月年,越来越大,该部分要设置就写成0/n的形式,不设置就写成*。示例:

0/5  *  *  *   *  *    每隔5s执行一次

*  0/5  *  *  *  *    每隔5s执行一次

0/30  0/1  *  *  *  *    间隔不是1min30s,而是30s。只能设置一个部分,若设置多个部分,只有第一个设置的部分有效

0/90  *  *  *  *  *     间隔不是90s,而是60s。若数值超过合法值,会自动用最大值代替。比如秒、分的最大值是60,时的最大值是24,日的最大值是31,月的最大值12。

只能设置整的。比如说要设置秒,那只能设置为0-60s;设置分,只能设置1-60min;不能设置为分+秒,不能带零头,必须是整的。

定时方法每隔指定时间,系统会自动调用、执行,不需要我们手动调用。

原文地址:https://www.cnblogs.com/chy18883701161/p/12664840.html