定時任務一般是項目中都需要用到的,可以用於定時處理一些特殊的任務。 在SpirngBoot中使用定時任務變的特別簡單,不需要再像SpringMVC一樣寫很多的配置,只需要在啟動類上增加一個@EnableScheduling注解即可。
啟動類開啟定時任務
1 //開啟定時任務 2 @EnableScheduling 3 @RestController 4 @SpringBootApplication 5 //設置掃描的包名 6 @ComponentScan(basePackages = {"com.preach.controller"}) 7 public class InchlifcApplication { 8 public static void main(String[] args) { 9 SpringApplication.run(InchlifcApplication.class, args); 10 } 11 }
使用定時任務的類上使用注解@Compoment
,在方法上使用注解@Scheduled
1 @Component 2 public class IndexController { 3 4 /** 5 * 時間間隔,每隔5秒執行一次 6 */ 7 @Scheduled(fixedRate = 5000) 8 public void task() { 9 System.out.println("現在時間是:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); 10 } 11 }
@Compoment
用來標明這是一個被Spring管理的Bean@Scheduled
是方法上注解,添加該注解的方法即為單個計划任務,有兩種方式可以定義:
-
@Scheduled(fixedRate = 3000)
通過@Scheduled聲明該方法是計划任務,使用fixedRate屬性每隔固定時間執行一次 -
@Scheduled(cron = "0 0/10 * * * ?")
使用cron表達式可按照指定時間執行,這里是每10分鍾執行一次;