@EnableScheduling 開啟對定時任務的支持
其中Scheduled注解中有以下幾個參數:
1.cron是設置定時執行的表達式,如 0 0/5 * * * ?每隔五分鍾執行一次 秒 分 時 天 月
2.zone表示執行時間的時區
3.fixedDelay 和fixedDelayString 表示一個固定延遲時間執行,上個任務完成后,延遲多長時間執行
4.fixedRate 和fixedRateString表示一個固定頻率執行,上個任務開始后,多長時間后開始執行
5.initialDelay 和initialDelayString表示一個初始延遲時間,第一次被調用前延遲的時間
配置類
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan({"com.xingguo.logistics.service.aspect")
@EnableScheduling
public class AopConfig{
}
service類
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TestService2 {
private static final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
//初始延遲1秒,每隔2秒
@Scheduled(fixedRateString = "2000",initialDelay = 1000)
public void testFixedRate(){
System.out.println("fixedRateString,當前時間:" +format.format(new Date()));
}
//每次執行完延遲2秒
@Scheduled(fixedDelayString= "2000")
public void testFixedDelay(){
System.out.println("fixedDelayString,當前時間:" +format.format(new Date()));
}
//每隔3秒執行一次
@Scheduled(cron="0/3 * * * * ?")
public void testCron(){
System.out.println("cron,當前時間:" +format.format(new Date()));
}
}
測試類
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestController {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
}
}