springboot中定时任务(@Scheduled)的用法

springboot中定时任务(@Scheduled)的用法

用于控制任务在某个指定时间执行,或者每隔一段时间执行。一般用在业务层的业务类中

使用前提

需要在启动类添加注解@EnableScheduling,开启定时任务功能,默认是关闭的。

用到注解@Scheduled的方法的类需将此类标记为Spring容器中的一个Bean如业务类添加注解@Service

注解@Scheduled的参数用法

1.@Scheduled(cron = "* * * * * ?")

秒 分 时 日 月 周 年

cron表达式中各个时间元素用空格分隔,至少有6个时间元素(第7个时间元素为年份可写可不写)

cron表达式支持占位符的写法,可以在配置文件或配置服务器中动态调整:

@Scheduled(cron = "${cron}")

常用的通配符说明:

"*" 表示所有值
"-" 表示区间
"?" 表示不指定值
"," 表示指定多个值
"/" 表示增量触发,例如秒元素中的"0/15" 表示从0秒开始,每15秒触发(0,15,30,45)

2.@Scheduled(fixedDelay = 50000, initialDelay = 1000)

参数说明:

fixedDelay = 5*1000 :上一次执行完毕时间点后5秒再次执行
fixedDelayString = "${service.fixed-delay:10000}" : 与fixedDelay作用相同,但表示形式为字符串并支持占位符,可以在配置文件或配置服务器中动态调整,可以设置默认值。
fixedRate = 5*1000 :上一次执行开始时间点后5秒再次执行
initialDelay = 10*1000 :第一次延迟10秒后再执行
上面两个同理可以加String后缀用字符串或者占位符表示参数。

具体实例

启动类

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

/**
 * @author Administrator
 */
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

业务类

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Administrator
 */
@Slf4j
@Service
public class TestSchedulingService {
    @Scheduled(cron = "0/10 * * * * ?")
    public void testTask1() {
        log.info("开始执行测试任务1-每隔10秒运行一次,当前时间为:{}",new Date());
    }

    @Scheduled(fixedDelay = 5*1000, initialDelay = 10*1000)
    public void testTask2() {
        log.info("开始执行测试任务2-延迟10秒后每隔5秒运行一次,当前时间为:{}",new Date());
    }

    @Scheduled(fixedDelayString = "${service.fixed-delay:50000}",initialDelayString = "${service.initial-delay:50000}")
    public void testTask3() {
        log.info("开始执行测试任务3-每隔1秒运行一次,当前时间为:{}",new Date());
    }
}

配置文件(yml文件,也可以配置在apollo或者nacos服务器中)

service.fixed-delay: 1000
service.initial-delay: 10000
posted @ 2021-11-19 15:49  柯南。道尔  阅读(5611)  评论(0编辑  收藏  举报