SpringBoot注解配置文件自动映射到属性 和 定时任务的使用

        1、常见定时任务 Java自带的java.util.Timer类
            timer:配置比较麻烦,时间延后问题
            timertask:不推荐

        2、Quartz框架
            配置更简单
            xml或者注解

        3、SpringBoot使用注解方式开启定时任务
            1)启动类里面 @EnableScheduling开启定时任务,自动扫描
            2)定时任务业务类 加注解 @Component被容器扫描
            3)定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期执行一次

不多说直接上代码

@Component //让Spring 扫描到这个
@PropertySource("classpath:application.yml") // 配置文件的路径
@ConfigurationProperties(prefix = "task") // 映射配置文件里面的那个节点
@EnableScheduling // 开启定时任务
public class TaskTest {

    @Scheduled(cron = "${cron.time}") //@Scheduled 那个方法开启定时任务  cron = "${cron.time}" 任务的时间
    public  void printTime(){
        System.err.println("当前时间:"+new Date());
    }
}

这样就OK 了

@PropertySource("classpath:application.yml") 

这个我用idea 的时候会有一个问题 说classpath not found 这里需要在pom文件中加入一个jar

<!--配置文件处理-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

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

这其中有多个属性cron 是一个表达式形式的,还有跟多的选择例如

@Scheduled(fixedRate = 2000)
@Scheduled(fixedRateString = "2000")
@Scheduled(fixedDelay = 2000)
@Scheduled(fixedDelayString = "2000")

fixedRate  这是两秒执行一次不管下面的执行是否完成

fixedDelay  这是两秒执行一次但是会等下面的方法执行完毕后再执行

cron:
  time: "*/2 * * * * *"

"*/2 * * * * *"  表示为2秒执行一次

这里有一个站长工具可以匹配时间

https://tool.lu/crontab/

发布了10 篇原创文章 · 获赞 0 · 访问量 515

猜你喜欢

转载自blog.csdn.net/DNCCCC/article/details/105031016