- 在启动类添加注解:@EnableScheduling //允许自动调用
@SpringBootApplication
@EnableScheduling //允许自动调用
public class ManageApplication {
public static void main(String[] args) {
SpringApplication.run(ManageApplication.class, args);
}
}
- 在需要使用任务调度的类上面加注解 @Component,使该类被Spring管理
import org.springframework.stereotype.Component;
@Component
public class Ds {
//方法1 {...}
//方法2 {...}
//....
}
3.任务调度的方法上面加注解 @Scheduled
-
cron属性:时间表达式
-
fixedRate属性:上一个调用开始后再次调用的延时(再次调用时不需要等上一个调用执行完成)
-
fixedDelay属性:上一个调用完成后再次调用的延时(再次调用时需要等上一个调用执行完成)
-
initialDelay属性:第一次调用时的延迟时间
属性 含义
fixedRate = 1000 每秒执行一次,单位毫秒
"0 0 10,14,16 * * ?" 每天10点、14点、16点 触发
"0 0/30 9-17 * * ?" 朝九晚五工作时间内每半小时触发
"0 0 12 ? * WED" 表示每个星期三中午12点触发
"0 0 12 * * ?" 每天中午12点触发
"0 15 10 ? * *" 每天上午10:15触发
"0 15 10 * * ?" 每天上午10:15触发
"0 15 10 * * ? *" 每天上午10:15触发
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发
"0 15 10 15 * ?" 每月15日上午10:15触发
"0 15 10 L * ?" 每月最后一日的上午10:15触发
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Ds {
//每1秒执行一次该方法
@Scheduled(fixedRate = 1000)
public void test() {
System.out.println("------定时调度------");
}
//每天12点执行一次该方法
@Scheduled("0 0 12 * * ?")
public void test2() {
System.out.println("------定时调度2------");
}
}
通常情况下,任务调度需要配合异步功能,所以类只需要再添加一个注解@EnableAsync
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.EnableAsync;
@Component
@EnableAsync
public class Ds {
//每1秒执行一次该方法
@Scheduled(fixedRate = 1000)
public void test() {
System.out.println("------定时调度------");
}
//每天12点执行一次该方法
@Scheduled("0 0 12 * * ?")
public void test2() {
System.out.println("------定时调度2------");
}
}