定时任务的是很常见的开发工作,在springboot中我们可以用注解很easy的实现。首先,需要加入@EnableScheduling注解开启定时任务功能,如下所示:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | @SpringBootApplication@EnableScheduling
 public class SpringbootAcTaskApplication {
 
 public static void main(String[] args) {
 SpringApplication.run(SpringbootAcTaskApplication.class, args);
 }
 
 }
 
 | 
然后使用@Scheduled注解来实现定时任务执行,如下所示:
| 12
 3
 4
 5
 6
 7
 8
 
 | @Componentpublic class ScheduleDemo {
 
 @Scheduled(cron = "${task.cron}")
 public void run() {
 System.out.println(" schedule running");
 }
 }
 
 | 
其中${task.cron}参数在配置文件中配置如下:
| 12
 
 | task:cron: 0/1 * * * * *
 
 | 
有关cron表达式的设定可参考《Cron表达式讲解》
当然@Scheduled注解还有其他参数可用,如fixedDelay、fixedRate等。
因为springboot有自动配置的功能,所以任务池也可以进行配置,如下所示:
| 12
 3
 4
 5
 
 | spring:task:
 scheduling:
 pool:
 size: 1
 
 |