springboot中执行定时任务

忘是亡心i 2022-10-02 01:49 413阅读 0赞

定时任务的是很常见的开发工作,在springboot中我们可以用注解很easy的实现。首先,需要加入@EnableScheduling注解开启定时任务功能,如下所示:

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class SpringbootAcTaskApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringbootAcTaskApplication.class, args);
  6. }
  7. }

然后使用@Scheduled注解来实现定时任务执行,如下所示:

  1. @Component
  2. public class ScheduleDemo {
  3. @Scheduled(cron = "${task.cron}")
  4. public void run() {
  5. System.out.println(" schedule running");
  6. }
  7. }

其中${task.cron}参数在配置文件中配置如下:

  1. task:
  2. cron: 0/1 * * * * *

有关cron表达式的设定可参考《Cron表达式讲解》

当然@Scheduled注解还有其他参数可用,如fixedDelayfixedRate等。

因为springboot有自动配置的功能,所以任务池也可以进行配置,如下所示:

  1. spring:
  2. task:
  3. scheduling:
  4. pool:
  5. size: 1

发表评论

表情:
评论列表 (有 0 条评论,413人围观)

还没有评论,来说两句吧...

相关阅读