@Scheduled教程1-- 指定线程池运行定时任务

本文介绍了如何在Spring中通过自定义线程工厂和ScheduledThreadPoolExecutor来配置定时任务的线程池,以实现多个任务并发执行。通过设置线程优先级和定制线程名称,提高了系统的并发性能和可读性。测试结果显示,使用自定义线程池后,任务执行时间相同,线程名称符合预期。
摘要由CSDN通过智能技术生成

1. 未指定线程池

需要注意的@Scheduled默认情况下只有一个线程,并不能同时运行多个任务,分析源码可以看到

运行demo 在控制台我们可以看到打印出来的线程名称

2. 指定线程池运行定时任务

自定义一个线程工厂继承ThreadFactory进行线程配置

package com.example.demo;

import lombok.extern.log4j.Log4j;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author jianglinmao
 */
@Log4j
public class MyThreadFactory implements ThreadFactory  {

    private final String namePrefix;
    private final int priority;

    /**
     * 线程池线程命名编号
     */
    private final AtomicLong sequenceNo = new AtomicLong(0);

    /**
     * 定义线程优先级
     * @param namePrefix
     * @param priority
     */
    public MyThreadFactory(String namePrefix, int priority) {
        this.namePrefix = namePrefix;
        if (priority < Thread.MIN_PRIORITY) {
            this.priority = Thread.MIN_PRIORITY;
        } else if (priority > Thread.MAX_PRIORITY) {
            this.priority = Thread.MAX_PRIORITY;
        } else {
            this.priority = priority;
        }
    }

    /**
     * 定义线程名称
     * @param runnable
     * @return
     */
    @Override
    public Thread newThread(Runnable runnable) {
        String threadName = String.format("%s-%d", namePrefix, sequenceNo.getAndIncrement());
        Thread thread = new Thread(runnable, threadName);
        thread.setDaemon(false);
        thread.setPriority(priority);
        thread.setUncaughtExceptionHandler((t, e) -> log.info( "UNCAUGHT in thread " + t.getName(), e));
        return thread;
    }
}

自定义一个定时线程池继承ScheduledThreadPoolExecutor

package com.example.demo;

import org.springframework.scheduling.support.DelegatingErrorHandlingRunnable;
import org.springframework.scheduling.support.ScheduledMethodRunnable;

import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author jianglinmao
 */
public class MySystemScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {

    public MySystemScheduledThreadPoolExecutor(int corePoolSize, String namePrefix, int priority) {
        super(corePoolSize, new MyThreadFactory(namePrefix, priority));
        super.setMaximumPoolSize(corePoolSize * 4);
    }

    @Override
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit) {
        return super.schedule(wrapScheduledRunnable(command), delay, unit);
    }

    @Override
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit) {
        return super.schedule(callable, delay, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
        return super.scheduleAtFixedRate(wrapScheduledRunnable(command), initialDelay, period, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit) {
        return super.scheduleWithFixedDelay(wrapScheduledRunnable(command), initialDelay, delay, unit);
    }

    /**
     * 仅对@Scheduled的代理runnable再包装一层代理
     */
    private Runnable wrapScheduledRunnable(Runnable runnable) {
        if (runnable instanceof DelegatingErrorHandlingRunnable || runnable instanceof ScheduledMethodRunnable) {
            return new StatisticableRunnable(runnable);
        }
        return runnable;
    }

}

重写配置项

package com.example.demo;

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

import java.util.concurrent.ScheduledExecutorService;

/**
 * @author jlm
 * @date 2021-01-28 16:08
 */
@Configuration
public class ScheduledConfig implements SchedulingConfigurer {

    private static final int SCHEDULE_POOL_SIZE = 64;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod = "shutdown")
    public ScheduledExecutorService taskExecutor() {
        return new MySystemScheduledThreadPoolExecutor(SCHEDULE_POOL_SIZE, "my-schedule-pool", Thread.MAX_PRIORITY);
    }


}

测试:

两个方法执行的时间相同,线程名称也不相同,并且线程名称是我们所定义的,说明已经成功指定使用自己定义的线程池

 

在 Spring Boot 中,我们可以使用 `@Scheduled` 注解来创建定时任务。该注解可以用于方法上,表示这个方法是一个定时任务。在方法上加上该注解后,Spring Boot 会自动创建一个定时任务,并按照指定的时间间隔执行该方法。 下面是一个简单的示例: ```java @Component public class MyTask { @Scheduled(fixedRate = 5000) public void run() { System.out.println("Hello, world!"); } } ``` 上面的代码中,我们定义了一个名为 `MyTask` 的类,它被标注为 `@Component`,表示这是一个组件类。该类内部还有一个名为 `run` 的方法,它被标注为 `@Scheduled(fixedRate = 5000)`,表示该方法是一个定时任务,每 5 秒钟执行一次。 除了 `fixedRate` 属性外,`@Scheduled` 注解还有其他许多属性可供配置,例如: - `fixedDelay`:表示上一次任务执行完后延迟多长时间再执行下一次任务。 - `initialDelay`:表示首次任务执行前延迟多长时间。 - `cron`:支持使用 cron 表达式来定制更复杂的执行时间规则。 下面是一个带有 `fixedDelay` 和 `initialDelay` 属性的定时任务示例: ```java @Component public class MyTask { @Scheduled(fixedDelay = 5000, initialDelay = 1000) public void run() { System.out.println("Hello, world!"); } } ``` 上面的代码中,我们将 `fixedDelay` 属性设置为 5000 毫秒,表示上一次任务执行完后延迟 5 秒钟再执行下一次任务;将 `initialDelay` 属性设置为 1000 毫秒,表示首次任务执行前延迟 1 秒钟。 最后,还要注意一点,使用 `@Scheduled` 注解创建的定时任务默认是单线程的,如果任务执行时间过长,会阻塞整个应用程序的运行。因此,在实际应用中,我们需要根据实际情况来控制任务的执行时间,或者使用线程池等机制来保证任务的并发执行。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值