【七日打卡】Spring定时任务介绍

简介: 定时任务一般会存在中大型企业级项目中,为了减少服务器、数据库的压力往往会采用时间段性的去完成某些业务逻辑。SpringBoot为我们内置了定时任务,我们只需要一个注解就可以开启定时为我们所用了。

定时任务一般会存在中大型企业级项目中,为了减少服务器、数据库的压力往往会采用时间段性的去完成某些业务逻辑。SpringBoot为我们内置了定时任务,我们只需要一个注解就可以开启定时为我们所用了。

通过@EnableScheduling@Scheduled开启定时功能

@Scheduled

  • 作用:spring定时器(定时执行一次或定时轮询执行一段代码)
  • 使用场景:注解在方法上

@EnableScheduling

  • 启用spring定时器功能。

定时器的参数写法

定时器的参数有两种写法是用cron表达式,或者使用fixedDelay、fixedRate等参数直接配置

第一种配置方式

项目启动后方法不会执行,而是等到执行周期到了才会执行方法

@Scheduled(cron = "0/5 * * * * ?")
public void execute() {
    log.info("ScheduleTask "+ Thread.currentThread().getName());
}
复制代码

第二种参数方式

项目启动成功后马上执行一次

@Scheduled(fixedRateString="1000")
public void execute() {
    log.info("ScheduleTask "+ Thread.currentThread().getName());
}
复制代码

Scheduled对于线程池的选择顺序

在项目中我们通常不会自己手动创建线程,而是通过统一的线程池来执行方法,使用这种方法来避免多人团队中由于自定义线程导致的资源耗尽的问题。在自定义线程池之前首先要了解Spring在执行异步任务或者方法的时候是怎么选择线程池的。

Scheduled对于线程池的选择顺序如下图所示:

4005d37034ac218a1bcf3a8a3c90a26.png

当Spring执行定时任务的时候,首先会在上下文中找类型为TaskScheduler或者名称为taskScheduler的bean,找不到的时候会手动创建一个线程执行此task。

如图分别定义了2个相同类型的线程池,只是bean 的名字不用

Himport cn.hutool.cron.task.Task;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler;
importorg.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
@author jiangpeng
@date 2021/1/1514:46
@Configuration
public class TaskschedulerPool {
@Bean
public TaskScheduler threadPoolTaskScheduler(){
finalThreadPoolTaskScheduler taskScheduler =new ThreadPoolTaskScheduler() taskScheduler.setPoolSize(10);
taskScheduler.setThreadNamePrefix("Async-threadPoolTaskScheduler-");//必须得先初始化,才能使用
taskScheduler.initialize(); return taskscheduler;}
@Bean 当存在同类型的bean时,schedule会选择这个名字的 
public TaskScheduler taskScheduler(){
final ThreadPoolTaskScheduler beaskscheduler = new ThreadpoolTaskscheduler();
taskScheduler.setPoolSize(10);
taskScheduler.setThreadNamePrefix("my-threadPoolTaskScheduler-"); return taskScheduler;

单元测试代码如下:

package com.mty.jls.scheduleTest;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
 * @author jiangpeng
 * @date 2021/1/1514:55
 */
@SpringBootTest( classes = {TaskSchedulerPool.class, AsyncApplicationTests.TestConfig.class} )
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
public class AsyncApplicationTests {
    @Test
    public void testCron() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Configuration
    @EnableScheduling
    public static class TestConfig {
        @Bean
        public ScheduleTask getScheduleTask() {
            return new ScheduleTask();
        }
        @Bean
        public ScheduleTask2 getScheduleTask2() {
            return new ScheduleTask2();
        }
    }
    @Component
    static class ScheduleTask {
        @Scheduled(fixedRateString="1000")
        public void execute() {
            log.info("ScheduleTask "+ Thread.currentThread().getName());
        }
    }
    @Component
    static class ScheduleTask2 {
        @Scheduled(fixedRateString="2000")
        public void execute() {
            log.info("ScheduleTask 2 "+ Thread.currentThread().getName());
        }
    }
}
复制代码

执行结果如图:

assed :1 ot 1 test -3s383M75
968[ my - threadPoolTaskScheduler -3]IIF0 c . m . j . s . AsyncApplicationTests - ScheduleIask 
 my - threadPoolTaskScheduler -3
968[ my - threadPoolTaskScheduler -1]IlF0 c . m . j . s . AsyncApplicationTests - ScheduleIask mythreadPoolIaskScheduler -1
968[ my - threadPoolTaskScheduler -1]IIF0 c . m . j . s . AsyncApplicationTests - ScheduleIask 2 my - threadPoolTaskScheduler -1
968[ my - threadPoolTaskScheduler -4]IF0 c . m . j . s . AsyncApplicationTests - ScheduleTask 
 myrthreadPoelTaskScheduler -4


相关文章
|
5月前
|
druid Java 数据库
Spring Boot的定时任务与异步任务
Spring Boot的定时任务与异步任务
|
5月前
|
Java 数据库 Spring
Spring Boot 实现定时任务的动态增删启停
Spring Boot 实现定时任务的动态增删启停
80 0
|
2月前
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
定时任务在企业应用中至关重要,常用于异步数据处理、自动化运维等场景。在单体应用中,利用Java的`java.util.Timer`或Spring的`@Scheduled`即可轻松实现。然而,进入微服务架构后,任务可能因多节点并发执行而重复。Spring Cloud Alibaba为此发布了Scheduling模块,提供轻量级、高可用的分布式定时任务解决方案,支持防重复执行、分片运行等功能,并可通过`spring-cloud-starter-alibaba-schedulerx`快速集成。用户可选择基于阿里云SchedulerX托管服务或采用本地开源方案(如ShedLock)
|
5月前
|
Java 调度 Maven
Spring Task 自定义定时任务类
Spring Task 自定义定时任务类
59 0
|
3月前
|
资源调度 Java 调度
Spring Cloud Alibaba 集成分布式定时任务调度功能
Spring Cloud Alibaba 发布了 Scheduling 任务调度模块 [#3732]提供了一套开源、轻量级、高可用的定时任务解决方案,帮助您快速开发微服务体系下的分布式定时任务。
14662 25
|
2月前
|
Java 开发者 Spring
Spring Boot实战宝典:揭秘定时任务的幕后英雄,让业务处理如流水般顺畅,轻松驾驭时间管理艺术!
【8月更文挑战第29天】在现代应用开发中,定时任务如数据备份、报告生成等至关重要。Spring Boot作为流行的Java框架,凭借其强大的集成能力和简洁的配置方式,为开发者提供了高效的定时任务解决方案。本文详细介绍了如何在Spring Boot项目中启用定时任务支持、编写定时任务方法,并通过实战案例展示了其在业务场景中的应用,同时提供了注意事项以确保任务的正确执行。
37 0
|
2月前
|
Dubbo Java 调度
揭秘!Spring Cloud Alibaba的超级力量——如何轻松驾驭分布式定时任务调度?
【8月更文挑战第20天】在现代微服务架构中,Spring Cloud Alibaba通过集成分布式定时任务调度功能解决了一致性和可靠性挑战。它利用TimerX实现任务的分布式编排与调度,并通过`@SchedulerLock`确保任务不被重复执行。示例代码展示了如何配置定时任务及其分布式锁,以实现每5秒仅由一个节点执行任务,适合构建高可用的微服务系统。
53 0
|
5月前
|
NoSQL Java Redis
Spring Boot 监听 Redis Key 失效事件实现定时任务
Spring Boot 监听 Redis Key 失效事件实现定时任务
122 0
|
3月前
|
SQL Java 调度
实时计算 Flink版产品使用问题之使用Spring Boot启动Flink处理任务时,使用Spring Boot的@Scheduled注解进行定时任务调度,出现内存占用过高,该怎么办
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
|
3月前
|
XML Java Linux
Spring Task 定时任务没有定时执行是为什么?
Spring Task 定时任务没有定时执行是为什么?
47 2
下一篇
无影云桌面