SpringBoot入門八,添加定時任務
阿新 • • 發佈:2018-10-08
pre ble 51cto block string 輸出 結束 boot fix
SpringBoot添加定時任務非常簡單,只需要兩步即可
1. SpringBoot啟動類 添加@EnableScheduling註解,開啟定時任務的配置
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * <h5>描述:springboot啟動類</h5> */ @SpringBootApplication @EnableScheduling // 開啟定時任務的配置 public class DemoApp { public static void main(String[] args) { // 整個程序入口,啟動springboot項目 SpringApplication.run(DemoApp.class, args); } }
2. 編寫定時任務類
註意在類上不要少了註解,要執行的方法上也不能少了註解,@Scheduled的使用方法請找度娘
import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TaskTest { //輸出時間格式 private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // 第一次執行前延時5秒啟動,每次任務結束後15秒再次啟動 @Scheduled(initialDelay = 5000, fixedDelay = 15000) private void sayHello() { System.out.println(format.format(new Date())+"向宇宙發出了一聲問候:Hello World!"); } }
效果
SpringBoot入門八,添加定時任務