SpringBoot开启定时任务

Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.

目录

概述

SpringBoot开启定时任务

需求:

设计思路

实现思路分析

1.Springboot 整合定时任务

demo 如下:

Spring Boot提供了一种非常简单和方便的方式来整合定时任务。以下是整合定时任务的步骤:

  1. 引入相关依赖:在pom.xml文件中添加spring-boot-starter-quartz依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
  1. 创建一个定时任务类:创建一个带有@Component注解的类,实现Job接口,并重写execute方法,该方法中编写定时任务的业务逻辑。
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

@Component
public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("定时任务执行中...");
    }
}
  1. 配置定时任务:在application.propertiesapplication.yml配置文件中添加相关的定时任务配置。
# 定时任务配置
spring.quartz.job-store-type=jdbc # 使用数据库存储定时任务
spring.quartz.jdbc.initialize-schema=always # 启动时自动初始化数据库表
spring.quartz.properties.org.quartz.threadPool.threadCount=10 # 定时任务线程池大小
  1. 启动定时任务:使用@EnableScheduling注解启用定时任务,这样Spring Boot会自动扫描并启动所有带有@Scheduled注解的定时任务。
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 MyJob {

    @Scheduled(cron = "0 0/5 * * * ?") // 每5分钟触发一次
    public void execute() {
        System.out.println("定时任务执行中...");
    }
}

通过以上步骤,就可以实现Spring Boot整合定时任务。在定时任务的执行过程中,可以使用Quartz提供的丰富功能来管理、调度和监控定时任务。

5.源码分析

Spring Boot 提供了一种简单的方式来创建和管理定时任务。在Spring Boot中,我们可以通过使用@EnableScheduling注解来开启定时任务的支持,并通过@Scheduled注解来定义具体的定时任务。

下面是一个示例的Spring Boot整合定时任务的源码分析:

首先,我们需要在启动类上添加@EnableScheduling注解来开启定时任务的支持。这样,Spring Boot就会自动扫描并创建定时任务。

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

接下来,我们可以在任意的Spring组件中定义定时任务。只需要在方法上添加@Scheduled注解,并指定定时任务的执行时间。

@Component
public class MyTask {

    // 每隔5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void myTask() {
        System.out.println("定时任务执行中...");
    }
}

在上面的例子中,我们定义了一个名为myTask的定时任务方法。通过设置fixedRate参数为5000,表示定时任务每隔5秒执行一次。

最后,在启动应用程序后,定时任务就会自动执行。我们可以在控制台上看到定时任务的执行结果。

总结一下,整合定时任务的过程主要包括以下几个步骤:

  1. 在启动类上添加@EnableScheduling注解来开启定时任务的支持。
  2. 在任意的Spring组件中定义定时任务的方法,通过@Scheduled注解指定定时任务的执行时间。
  3. 启动应用程序,定时任务就会自动执行。

以上就是Spring Boot整合定时任务的源码分析。通过使用@EnableScheduling和@Scheduled注解,我们可以很方便地创建和管理定时任务。

@EnableScheduling是一个用于开启Spring的定时任务功能的注解。它可以放在Spring Boot应用的主类上,以启用定时任务的功能。

@Scheduled注解用于将方法标记为一个定时任务,并指定定时任务的执行规则。它可以放在类的方法上,用于指定方法的执行时间和频率。

@Scheduled注解有多个可选参数,包括cron、fixedDelay、fixedRate、initialDelay等。这些参数可以根据需求来设置定时任务的执行规则。

例如,使用@Scheduled(cron = “0 0 0 * * ?”)注解可以将某个方法指定为每天凌晨0点执行的定时任务。

需要注意的是,@EnableScheduling注解必须在Spring应用的主类上添加,才能启用定时任务的功能。而@Scheduled注解则可以放在任意Spring组件的方法上,用于指定定时任务的执行规则。

@EnableScheduling@Scheduled是Spring框架中用于支持定时任务的注解。

@EnableScheduling注解是一个启用定时任务的注解,通常与@Configuration注解一起使用。它会启用Spring的任务执行器,并扫描应用中带有@Scheduled注解的方法。

@Scheduled注解用于标注一个方法是一个定时任务执行方法。它可以接受多种参数来配置定时任务的执行规则,如cron表达式、fixed rate、fixed delay等。

下面是对这两个注解的源码分析:

  1. @EnableScheduling注解的源码如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(SchedulingConfiguration.class)
public @interface EnableScheduling {
}

从源码可以看出,@EnableScheduling注解是一个元注解,它被@Import注解修饰,并引入了SchedulingConfiguration类。

  1. SchedulingConfiguration类的源码如下:
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class SchedulingConfiguration {

    @Bean(TriggerTaskRegistrar.BEAN_NAME)
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public TriggerTaskRegistrar taskRegistrar(ScheduledTaskRegistrar taskRegistrar) {
        return new TriggerTaskRegistrar(taskRegistrar);
    }

    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }
}

从源码可以看出,SchedulingConfiguration类被@Configuration注解修饰,它定义了两个Bean:

  • taskRegistrar:通过ScheduledTaskRegistrar类创建一个TriggerTaskRegistrar对象。TriggerTaskRegistrar是用于注册和管理定时任务的对象。
  • scheduledAnnotationProcessor:创建一个ScheduledAnnotationBeanPostProcessor对象,用来处理带有@Scheduled注解的方法。
  1. @Scheduled注解的源码如下:
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled {

    String CRON_DISABLED = "-";

    String cron() default "";

    String zone() default "";

    long fixedDelay() default -1;

    String fixedDelayString() default "";

    long fixedRate() default -1;

    String fixedRateString() default "";

    long initialDelay() default -1;

    String initialDelayString() default "";
}

从源码可以看出,@Scheduled注解是一个元注解,它可以标注在方法和注解类型上。它定义了一些属性来配置定时任务的执行规则,如cron表达式、fixed delay、fixed rate、initial delay等。

以上就是@EnableScheduling@Scheduled注解的基本源码分析。

参考资料和推荐阅读

参考资料
官方文档
开源社区
博客文章
书籍推荐

  1. https://www.cnblogs.com/brickMovingWorker/p/17246720.html

欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!同时,期望各位大佬的批评指正~,如果有兴趣,可以加文末的交流群,大家一起进步哈

  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中开启定时任务,你可以按照以下步骤进行操作: 1. 在启动类上使用`@EnableScheduling`注解来开启定时任务功能。例如: ```java @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 2. 在需要定时执行的方法上添加`@Scheduled`注解,并指定cron表达式来设置定时任务的触发时间。例如: ```java @Scheduled(cron = "*/6 * * * * ?") public void sayHello() { System.out.println("hello"); } ``` 上述示例中的`cron = "*/6 * * * * ?"`表示每隔6秒执行一次`sayHello()`方法。 这样,当你启动Spring Boot应用程序时,定时任务将自动开始执行。注意,定时任务的触发时间是按照cron表达式来设定的,根据你的需求进行调整即可。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot实现定时任务的三种方式](https://blog.csdn.net/m0_67401761/article/details/126114619)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Spring boot开启定时任务的三种方式](https://blog.csdn.net/qianlixiaomage/article/details/106599951)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [玩转SpringBoot定时任务详解](https://blog.csdn.net/weixin_30376163/article/details/97999503)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值