springboot greatly simplifies the configuration of the previous spring timer. Now configure the timer only need two steps:
1, add annotations @EnableScheduling in application startup class
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping(value = "/") public String defaultMapping(){ return "welcome" ; } }
2, the configuration of the timer config java class, specify execution frequency and the execution logic
package com.example.demo.javaConfig; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.Scheduled; import java.text.SimpleDateFormat; import java.util.Date; @Configuration public class ScheduleStandTest { // expression second month time-day week (available 1-7 weeks, said Sunday the first day is also available in English before 3 SUN) @Scheduled(cron = "0 0/1 * * * ?") public void doExcute(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String nowStr = sdf.format(new Date()); System.out.println(nowStr); } }
Execution results are as follows