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