定时任务在配置类上添加@EnableScheduling开启对定时任务的支持,在相应的方法上添加@Scheduled声明需要执行的定时任务。
其中Scheduled注解中有以下几个参数:
- cron
- zone
- fixedDelay和fixedDelayString
- fixedRate和fixedRateString
initialDelay和initialDelayString
1.cron是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次
2.zone表示执行时间的时区
3.fixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行
4.fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行
5.initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间
配置类
package com.xingguo.logistics.controller;
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类
package com.xingguo.logistics.service.aspect;
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()));
}
}
测试类
package com.xingguo.logistics.controller;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestController {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
}
}
测试结果: