springboot多线程定时任务
Posted _Lawrence
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot多线程定时任务相关的知识,希望对你有一定的参考价值。
package com.llf.config; 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(5); // 设置最大线程数 executor.setMaxPoolSize(10); // 设置队列容量 executor.setQueueCapacity(20); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); // 设置默认线程名称 executor.setThreadNamePrefix("lawrence-"); // 设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); return executor; } }
多线程异步执行
package com.llf.utils; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class Text { @Async public void sayHellot(int i){ System.out.println(i+"---"+System.currentTimeMillis()); } }
定时执行,时间设置参考:https://www.cnblogs.com/xiang--liu/p/11378860.html
package com.llf.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @EnableScheduling @Lazy(false) public class Sd { @Autowired Text text; @Scheduled(cron = "*/2 * * * * ?") public void text(){ text.sayHellot(1); } }
以上是关于springboot多线程定时任务的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot几种定时任务的实现方式 和多线程执行任务