2

如何使用 Spring Boot Scheduler 计划和安排任务/作业?

 1 year ago
source link: https://www.jdon.com/66332.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何使用 Spring Boot Scheduler 计划和安排任务/作业?
有时我们会遇到这样一种情况,我们希望任务只在特定时间点执行或在特定时间间隔内重新执行。同时,我们的客户希望在特定时间以每小时、每天、每周、每月或什至其他方式执行功能。事实上,在所有这些类型的情况下,我们都会实施调度来相应地满足要求。例如,最流行的实现之一是在特定时间生成报告。

Spring Boot 对调度有最好的支持,我们可以相应地通过简单直接的步骤实现相同的调度。

调度就是我们可以在特定的时间间隔内执行一个任务而无需人工干预的过程。换句话说,我们可以说调度是一个基于时间段或时间点循环执行任务的过程。例如,假设我们的任务是每天上午 9:30 生成报告。然后我们可以在这里应用调度技术来相应地满足我们的要求。

再举个例子,如果我们想在特定的时间间隔内将特定的数据或文件发送到另一个应用程序,那么我们可以使用调度来完成。此外,我们可以使用日程安排的地方包括月度银行对账单、工资单生成、保险支付、电费账单、办公室每日站立会议、Sprint 计划等。

Period of time 和 Point of time 和有什么不一样?
Period of time 讲的是时间间隔。它没有开始日期/时间。例如。1 小时 24 分钟 3 天 4 个月 40 秒等

Point of time 谈论特定的时间。此外,它还有开始日期/时间。例如。上午 4 点、8 月 15 日、1 月 26 日上午 9:00 等

如何在 Spring Boot 中实现调度:

  • 第 1 步:创建Spring Boot 入门项目:无需添加任何其他入门依赖项。
  • 第 2 步 :在 Starter 类应用 @EnableScheduling
    @SpringBootApplication
    @EnableScheduling
    public class SpringBootSchedulingApplication {
    
        public static void main(String args) {
            SpringApplication.run(SpringBootSchedulingApplication.class, args);
        }
    
    }
    
  • 第 3 步:另外,定义一个类并在类上应用 @Component
    @Component
    public class SchedulerServiceOne {
        
        public void scheduledMethod() {
            System.out.println("Hello Scheduler One :" +new Date());
        }
    }
    
  • 第 4 步:最后,相应地在上面的类中实现一个方法,该方法执行任务并应用@Scheduled(………………)
    @Component
    public class SchedulerServiceOne {
        
        @Scheduled(initialDelay = 5000, fixedDelay = 9000) 
        // 1000 milli sec = 1sec
        public void scheduledMethod() {
            System.out.println("Hello Scheduler One :" +new Date());
        }
    }
    

@Scheduled是什么?
此注释指示 Spring 容器根据提供的参数在循环中执行该方法,直到应用程序/服务器停止。但是,它使用以下概念来支持调度。

  • 1) 固定延迟fixedDelay 
  • 2) 固定速率fixedRate
  • 3) cron 表达式

fixedRate 和 fixedDelay 支持时间段。但是,Cron 表达式支持时间段和时间点。

注意:同样重要的是,你不能在括号中没有任何输入的情况下编写@Scheduled,否则 Spring 容器将抛出 IllegalStateException: Encountered invalid @Scheduled method 'generateReport': Exactly one of the 'cron', 'fixedDelay(String)' , 或 'fixedRate(String)' 属性是必需的。

@Scheduled 是在运行时应用的方法级别注解,用于标记要调度的方法。任何使用@Scheduled 的方法都需要满足两个条件:

  • 1)被注解的方法不应该有返回类型。否则返回值将在运行时被忽略。
  • 2)被注解的方法不应接受任何输入参数。

固定延迟fixedDelay 
我们可以通过两种方式提供固定延迟输入:整数和字符串(为了说明,请看上面的代码示例)

  • 整数类型:@Scheduled(fixedDelay = 1000)
  • 字符串类型:@Scheduled(fixedDelayString = “1000”)

fixedRate 表示方法调用之间的最大时间间隔。

固定速率fixedRate
fixedRate 表示方法调用之间的最大时间间隔。

@Scheduled(fixedRate=1000)

使用 cron 表达式
由于 Cron 表达式在 Unix/Linux 操作系统中非常流行用于调度,这里 Spring boot 内部也包含相同的概念。

@Scheduled(cron = "15 * * * * *")

 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK