如何在SpringBoot中实现定时任务?

本文介绍了如何在SpringBoot项目中利用内置的@Scheduled注解创建定时任务,并提供了使用application.properties或yml配置定时任务参数的示例,以及提及了使用Quartz作为替代框架的参考链接。
摘要由CSDN通过智能技术生成

在SpringBoot中实现定时任务,可以使用Spring自带的@Scheduled注解或者使用第三方库如Quartz。这里以使用@Scheduled为例,介绍如何在SpringBoot中实现定时任务。

  1. 在SpringBoot项目的主类上添加@EnableScheduling注解,开启定时任务功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 创建一个定时任务类,并在需要执行定时任务的方法上添加@Scheduled注解:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyTask {

    @Scheduled(cron = "0/5 * * * * ?") // 每5秒执行一次
    public void execute() {
        System.out.println("定时任务执行:" + new Date());
    }
}
  1. 在application.properties或application.yml中配置定时任务的参数,例如:
# application.properties
spring.task.scheduling.pool.size=10 # 定时任务线程池大小
spring.task.scheduling.shutdown=true # 是否允许关闭定时任务线程池
# application.yml
spring:
  task:
    scheduling:
      pool:
        size: 10 # 定时任务线程池大小
      shutdown: true # 是否允许关闭定时任务线程池
  1. 启动SpringBoot项目,定时任务会自动执行。

注意:如果使用Quartz作为定时任务框架,可以参考官方文档进行配置和使用:http://www.quartz-scheduler.org/documentation/quartz-2.3.0/quick-start.html

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值