顾乔芝士网

持续更新的前后端开发技术栈

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

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

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言