SpringBoot添加定时器

方法一:通过springboot自带入口来开启定时器。

首先我们都知道,springboot有一个自己的入口,也就是@SpringBootApplication(他是一个组合注解 由@Configuration,@EnableAutoConfiguration和@ComponentScan组成)。

首先定时器需要有一个总开关,因为可能要定时很多函数,如果我想全都暂时关上总不能一个一个把注解给删掉吧。所以我们需要先把总开关打开,也就是在springboot的入口处添加@EnableScheduling这个注解。上代码(此为springboot的入口)

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

  

总开关添加好后,我们只需要对需要定时方法进行配置即可,使用注解@Scheduled(cron = "0/2 * * * * *") 后面为Cron表达式。表示每2秒执行一次。
@Scheduled(cron = "0/2 * * * * *")  
public void timer(){  
    //获取当前时间  
    LocalDateTime localDateTime =LocalDateTime.now();  
    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
}

  

posted @ 2022-03-09 15:33  红尘沙漏  阅读(545)  评论(0编辑  收藏  举报