springboot中执行定时任务

本文介绍如何在SpringBoot中使用@EnableScheduling和@Scheduled注解实现定时任务,包括配置cron表达式、设置任务池大小及使用fixedDelay和fixedRate参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定时任务的是很常见的开发工作,在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注解还有其他参数可用,如fixedDelayfixedRate等。

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

spring:
  task:
    scheduling:
      pool:
        size: 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值