欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【2020年最后一篇日志】SpringBoot中用多线程执行定时任务

程序员文章站 2022-06-23 11:16:09
刚开始接触SpringBoot的时候就想用多线程执行一些定时任务,但是一直没有实现,因为它总是在run方法中提示注入的资源是无效的。让人头疼,一直没有好的解决办法。直到今天才发现他的解决办法-异步执行多线程。启动方式 @Scheduled(cron = "*/10 * * * * ?") // 每秒钟启动 0 0 23 * * ? 0 */1 * * * ? 0 0 8 * * ?public void trackMailedJob() {for (int i = 0; i....

刚开始接触SpringBoot的时候就想用多线程执行一些定时任务,但是一直没有实现,因为它总是在run方法中提示注入的资源是无效的。让人头疼,一直没有好的解决办法。直到今天才发现他的解决办法-异步执行多线程。

  • 启动方式
    @Scheduled(cron = "*/10 * * * * ?") // 每秒钟启动 0 0 23 * * ? 0 */1 * * * ? 0 0 8 * * ?
	public void trackMailedJob() {
		
		for (int i = 0; i < 10; i++) {
			TestThread2 testThread2 = new TestThread2();
			testThread2.start();
		}
	}
  • 报错如下 jdbcTemplate是null
    【2020年最后一篇日志】SpringBoot中用多线程执行定时任务

  • 之后我又换了一种方式,没报错,但是不是多线程
    【2020年最后一篇日志】SpringBoot中用多线程执行定时任务

真正使用多线程的方式如下!

  • 先写这样一个配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.util.concurrent.ThreadPoolExecutor;
 
@Configuration
@EnableAsync
public class AsyncConfig {
 
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(6);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("test-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
 
}
  • 写一个定时任务
@Log
@Component
public class TrackJobThreads {

	@Autowired
	private TestThread2 testThread;

	@Scheduled(cron = "*/37 * * * * ?") // 每秒钟启动 0 0 23 * * ? 0 */1 * * * ? 0 0 8 * * ?
	public void trackMailedJob() {
		 //  10个线程是不起效的 它取决于 executor.setCorePoolSize(6);
		 // 所以才有下面的打印结果  线程数不超过6个
		for (int i = 0; i < 10; i++) {
			testThread.run();  
     
		}
	}
}
  • 核心-多线程类TestThread2
@Async
	public synchronized void run() {
		log.info("你好呀"+TimeUtil.transfLongToTimeStr(Clock.systemUTC().millis()));
		try {
			Thread.currentThread().sleep(1000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
  • 运行结果:

【2020年最后一篇日志】SpringBoot中用多线程执行定时任务

  • 成功了,再见了2020.

本文地址:https://blog.csdn.net/weixin_39076203/article/details/112042779