文章目录
近期一个项目需要用到简单的定时任务,需要支持配置文件里修改 执行周期。记录如下 maven依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
|
关键代码
1 2 3 4 5 6 7 8
| @Bean public SchedulingConfigurer schedulingConfigurer(){ return new SchedulingConfigurer() { @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.addCronTask(runnable,schedule); } }; }
|
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package com.example;
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@SpringBootApplication @EnableScheduling public class DemoApplication {
@Value("${demo.schedule}") String schedule;
public static void main(String[] args){ SpringApplication.run(DemoApplication.class, args); }
@Bean public SchedulingConfigurer schedulingConfigurer(){ return new SchedulingConfigurer() { @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.addCronTask(runnable,schedule); } }; }
Runnable runnable = new Runnable() { int i; @Override public void run() { System.out.println("runing " + ++i); } };
}
|
在application.properties里加一行
1
| demo.schedule=*/3 * * * * ?
|
这个表示 每3秒执行一次。