定时任务 spring scheduler
使用场景:单机环境下处理定时任务
**************************
相关注解
@EnableScheduling
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({SchedulingConfiguration.class})
@Documented
public @interface EnableScheduling {
}
@Scheduled
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
String CRON_DISABLED = "-";
String cron() default ""; //cron只能识别6位,使用7位会报错
String zone() default "";
long fixedDelay() default -1L;
String fixedDelayString() default "";
long fixedRate() default -1L;
String fixedRateString() default "";
long initialDelay() default -1L;
String initialDelayString() default "";
}
**************************
示例
***************
config 层
SchedulerConfig
@Configuration
@EnableScheduling
public class SchedulerConfig {
@Bean
public TaskScheduler initTaskScheduler(){
ThreadPoolTaskScheduler taskScheduler=new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);
//默认为1.如果有多个任务,需重新设置poolsize的大小
taskScheduler.initialize();
return taskScheduler;
}
}
说明:使用注解@EnableScheduling使注解@Schedule生效
***************
service 层
HelloService
@Service
public class HelloService {
@Resource
private TaskScheduler taskScheduler;
public void task(){
taskScheduler.scheduleWithFixedDelay(()->{
System.out.println("task开始执行:"+System.currentTimeMillis());
}, Instant.now().plusSeconds(10), Duration.ofSeconds(5));
}//说明,该方法需手动调用才会触发执行
@Scheduled(initialDelay = 10,fixedDelay = 5)
public void task2(){
System.out.println("task2 开始执行:"+System.currentTimeMillis());
try{
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("task2 运行结束:"+System.currentTimeMillis());
}
@Scheduled(cron = "1/10 * * * * ?")
public void task3(){
System.out.println("task3 开始执行:"+System.currentTimeMillis());
try{
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("task3 运行结束:"+System.currentTimeMillis());
}
}
说明:注解@Schedule标注的方法在应用启动后,无需调用会自动执行
***************
controller 层
HelloController
@RestController
public class HelloController {
@Resource
private HelloService helloService;
@RequestMapping("/hello")
public String hello(){
System.out.println("开始调用 task任务:"+System.currentTimeMillis());
helloService.task();
return "success";
}
@RequestMapping("/hello2")
public String hello2(){
helloService.task2();
return "success 2";
}
@RequestMapping("/hello3")
public String hello3(){
helloService.task3();
return "success 3";
}
}
**************************
控制台输出
/hello
开始调用 task任务:1577240241404
task开始执行:1577240251417
task开始执行:1577240256420
task开始执行:1577240261438
task开始执行:1577240266456
task开始执行:1577240271467
task2、task3不需要调用,会自动执行
task2 开始执行:1577240763448
task2 运行结束:1577240765453
task2 开始执行:1577240765461
task2 运行结束:1577240767468
task2 开始执行:1577240767486
task2 运行结束:1577240769510
task2 开始执行:1577240769533
task3 开始执行:1577240771011
task2 运行结束:1577240771549
task2 开始执行:1577240771569
task3 运行结束:1577240773017
....