spring定时任务Scheduled与定时任务线程池配置SchedulingConfigurer ,Java

本文围绕Spring定时任务及线程池配置展开。介绍了Spring默认定时任务的使用,指出不必将@EnableScheduling注解放在主应用上,添加到使用定时任务的类上并在任务函数加@Scheduled即可。还提到Spring默认线程池只有1个线程,可配置SchedulingConfigurer启动多线程任务池。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring定时任务Scheduled与定时任务线程池配置SchedulingConfigurer ,Java

spring默认定时任务的使用

package zhangphil.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@EnableScheduling
public class MyScheduledTask {
    private int a = 0;
    private int b = 0;

    @Scheduled(fixedRate = 1000 * 3, initialDelay = 1000 * 6)
    private void simpleScheduled1() {
        log.info("定时1-{}", a++);
    }

    @Scheduled(fixedRate = 1000 * 3, initialDelay = 1000 * 6)
    private void simpleScheduled2() {
        log.info("定时2-{}", b++);
    }
}

输出:

有说法认为需要把@EnableScheduling注解放在主应用Application上,其实不必,只需要把@EnableScheduling添加到使用定时任务的类上,然后在类的内部定时任务函数上添加注解@Scheduled即可。

定时任务的线程池配置

spring默认会创建一个只有1个线程任务的线程池启动定时任务,观察上面的输出也可以看到,这个线程的名称叫scheduling-1。试想假设项目中的线程任务很多时候,1个线程的线程池就不够了。可以通过配置线程池的SchedulingConfigurer参数,实现启动多个线程任务的线程池容纳定时任务:

package zhangphil.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Configuration
public class MySchedulingConfigurer implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //设定长度5的定时任务线程池
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        taskRegistrar.setScheduler(scheduledExecutorService);
    }
}

输出:

 可以看出此时启动的定时任务归属到不同的子线程中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值