適用於Sping3.1以後的版本,首先通過註解@EnableScheduling開啓對計劃任務的支持,然後在計劃任務的方法上添加註解@Scheduled來申明這是一個計劃任務。
Spring通過@Scheduled支持多種類型的計劃任務,包含cron,fixDelay,fixRate等
demo~
1.計劃任務執行類
package com.xjj.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; /** * SpringBoot * Created by xian.juanjuan on 2017-6-12 14:02. */ @Service public class ScheduledTaskService { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss"); @Scheduled(fixedDelay = 2000) public void runFixedRateTime(){ System.out.println("每隔兩秒執行一次"+dateFormat.format(new Date())); } @Scheduled(cron = "0 2 14 ? * *")//每天14點12分執行,cron是Linux和Unix系統下的定時任務 public void runCron(){ System.out.println("在指定時間執行"+dateFormat.format(new Date())); } }
2.配置類
package com.xjj.task; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; /** * SpringBoot * Created by xian.juanjuan on 2017-6-12 14:08. */ @Configuration @ComponentScan("com.xjj.task") @EnableScheduling public class ScheduledConfig { }
3.運行
package com.xjj.task; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * SpringBoot * Created by xian.juanjuan on 2017-6-12 14:09. */ public class Main { public static void main(String[] args){ new AnnotationConfigApplicationContext(ScheduledConfig.class); } }結果