Spring Schedule定时用法详解

java开发的小伙伴们在业务开发中需要用到执行定时任务的情况下非常多,今天就介绍下使用Spring Schedule来做定时任务。

简介

Spring Schedule是一个强大的工具,用于在Java应用程序中调度和执行定时任务。通过使用Spring Schedule,开发者可以轻松地创建和管理定时任务,而无需依赖外部的调度框架或服务。本文将详细介绍如何在Spring项目中配置和使用Scheduled任务。

1. 添加依赖

首先,确保你的项目已经包含Spring Boot Starter依赖。如果还没有,请在你的pom.xml文件中添加以下内容:


    
    
        org.springframework.boot
        spring-boot-starter
    
    
    
        org.springframework.boot
        spring-boot-starter
    

2. 启用定时任务

在Spring Boot应用的主类上添加@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);
    }
}

3. 创建定时任务

创建一个带有@Scheduled注解的方法来定义定时任务。你可以指定多种不同的时间表达式来控制任务的执行频率。

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTasks {

    // 每5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void scheduleFixedRateTask() {
        System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
    }

    // 每隔10秒执行一次
    @Scheduled(fixedDelay = 10000)
    public void scheduleFixedDelayTask() {
        System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
    }

    // 每天上午10点执行一次
    @Scheduled(cron = "0 0 10 * * ?")
    public void scheduleTaskUsingCronExpression() {
        System.out.println("Cron task - " + System.currentTimeMillis() / 1000);
    }
}

4. 参数详解

fixedRate

fixedRate属性表示任务之间的固定时间间隔,单位为毫秒。无论任务执行需要多长时间,下一个任务都会在前一个任务完成后等待指定的时间间隔后开始。

fixedDelay

fixedDelay属性表示前一个任务完成后到下一个任务开始之间的固定时间间隔,单位为毫秒。如果任务执行时间超过了指定的延迟时间,那么下一次执行将在任务完成后立即开始。

cron表达式

cron属性允许你使用标准的cron表达式来定义复杂的调度规则。例如:

  • "0 0 12 * * ?": 每天中午12点执行一次。
  • "*/5 * * * * ?": 每5秒执行一次。
  • "0 0/5 14 * * ?": 每天下午2点到2:55之间,每5分钟执行一次。

5. 动态修改定时任务

有时候,你可能需要在运行时动态地修改定时任务的执行频率或其他属性。可以通过编程方式实现这一点。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;

@Component
public class DynamicTaskScheduler {

    @Autowired
    private TaskScheduler taskScheduler;

    private ScheduledFuture scheduledFuture;

    public void startScheduledTask() {
        Runnable task = () -> {
            System.out.println("Dynamically scheduled task - " + new Date());
        };
        CronTrigger trigger = new CronTrigger("0/10 * * * * ?"); // 每10秒执行一次
        scheduledFuture = taskScheduler.schedule(task, trigger);
    }

    public void stopScheduledTask() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(false); // 取消任务,但不允许正在执行的任务被中断
        }
    }
}

6. 注意事项

  • 线程池:默认情况下,Spring使用一个简单的单线程调度器来执行定时任务。如果你的应用有多个定时任务,并且这些任务需要并发执行,建议配置一个更大的线程池。可以在application.properties或application.yml中进行配置:
spring.task.execution.pool.core-size=5
spring.task.execution.pool.max-size=10
spring.task.execution.pool.queue-capacity=25
spring.task.execution.pool.keep-alive=60s
  • 事务管理:默认情况下,定时任务不会开启事务支持。如果需要在定时任务中使用事务,可以手动开启:
import org.springframework.transaction.annotation.Transactional;

@Component
public class MyTransactionalScheduledTasks {

    @Transactional
    @Scheduled(fixedRate = 5000)
    public void transactionalTask() {
        // Your database operations here
        System.out.println("Transactional task executed at " + System.currentTimeMillis() / 1000);
    }
}
  • 异常处理:确保在定时任务中妥善处理异常,以避免由于未捕获的异常导致整个应用崩溃。可以使用try-catch块来捕获并处理异常。

7. 示例项目结构

以下是一个简单的Spring Boot项目的结构示例,展示了如何组织定时任务相关的代码:

src
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── Application.java
    │               ├── config
    │               │   └── SchedulerConfig.java
    │               └── service
    │                   └── MyScheduledTasks.java
    └── resources
        └── application.properties

创作不易,如果这篇文章对你有用,欢迎点赞关注加评论哦。

相关文章

Java项目中的定时任务调度:掌控时间的艺术

Java项目中的定时任务调度:掌控时间的艺术在Java项目的世界里,时间管理是一个至关重要的技能。就像一个熟练的乐队指挥家需要掌握每一件乐器的演奏时机一样,程序员也需要精通如何安排代码的执行时刻。今天...

Java---定时任务的实现方式

一 什么是定时任务见名知意,定时任务就是每隔一段时间执行一次这个任务,比如我们日常生活中的下课铃,或者是闹钟等等,就是在设置好的固定时间段去不断执行这个任务。二 如何实现定时任务功能这次我介绍两种执行...

再见 Spring Task,这个定时任务框架真香

最近有朋友问到定时任务相关的问题。于是,我简单写了一篇文章总结一下定时任务的一些概念以及一些常见的定时任务技术选型。希望能对小伙伴们有帮助!个人能力有限。如果文章有任何需要补充/完善/修改的地方,欢迎...

java的定时任务解决方案有哪些?你会几种?

一、 业务中的定时任务,java语言有哪些解决方案产品经理说要定时发邮件,定时修改积分,定时发送短信。在我们的开发过程中,经常需要用到定时任务。像php,python,sh,这些脚本语言,一般是配合l...

JAVA架构师之路-教你如何去实现一个分布式定时任务

什么是分布式定时任务:首先,我们要了解计划任务这个概念,计划任务是指由计划的定时运行或者周期性运行的程序。我们最常见的就是Linux的‘crontab’和Windows的‘计划任务’。那么什么是分布式...