SpringBoot开启注解调用定时任务

平常项目中,会涉及一些定时任务,比如定时获取时间,发送短信邮箱,提醒我待办事项等等,下面说说Spring定时器的使用方法,这里以SpringBoot项目为例

1 启动类SpringBootApplication加上注解@EnableScheduling开启定时任务

@EnableScheduling //开启定时任务注解
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplication {
          
   
    public static void main(String[] args) {
          
   
        SpringApplication.run(SpringBootApplication.class, args);
    }
}

2给需要定时执行的任务方法加上注解配置参数

@Controller
public class TimeTestController {
          
   
    @Scheduled(cron = "*/5 * * * * ?")//每个5秒执行一次任务(方法)
    public void  timeScheduled(){
          
   
        Date dd=new Date();
        //格式化
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间:"+dateFormat.format(new Date()));
    }
}

3 启动项目查看效果

经验分享 程序员 微信小程序 职场和发展