• 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")));  
    }
    

      

  • 相关阅读:
    .net中Timer的使用
    计算日期的神器
    求全排列函数next_permutation
    各种排序
    求最大字段和
    炸弹时间复位
    最少步数,广搜
    数据
    水池数目
    最大岛屿
  • 原文地址:https://www.cnblogs.com/xianz666/p/15985393.html
Copyright © 2020-2023  润新知