Spring或SpringBoot项目随项目启动而启动线程执行特定任务的方法

简介: 项目启动,你是否有需求需要某个任务能随着项目启动就去执行某个任务呢?

当然方法不止一种    如注解:@PostConstruct   或者springBoot项目实现 ApplicationRunner


importcom.gpyh.gms.server.service.goods.GoodsInfoSynchService;importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.ApplicationListener;
importorg.springframework.context.annotation.DependsOn;
importorg.springframework.context.event.ContextRefreshedEvent;
importorg.springframework.stereotype.Component;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
@Component//@DependsOn({"需要依赖的类(启动的线程,需要在这个类后面完成初始化可添加)"})publicclassMyApplicationListenerimplementsApplicationListener<ContextRefreshedEvent> {
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyApplicationListener.class);
@AutowiredprivateGoodsInfoSynchServicegoodsInfoSynchService;
@OverridepublicvoidonApplicationEvent(ContextRefreshedEventevent) {
// 创建单线程池ExecutorServiceexecutor=Executors.newSingleThreadExecutor();
logger.info("线程启动监控");
executor.execute(()->**需要执行的任务**);
    }
}

importorg.springframework.stereotype.Component;
importjavax.annotation.PostConstruct;
@ComponentpublicclassQueueMonitor {
@PostConstructpublicvoidstartQueueMonitor() {
Threadthread=newThread(newYourQueueMonitorRunnable());
thread.start();
    }
privateclassYourQueueMonitorRunnableimplementsRunnable {
@Overridepublicvoidrun() {
// 监控队列的逻辑        }
    }
}
目录
相关文章
|
5天前
|
人工智能 JSON 前端开发
Spring Boot解决跨域问题方法汇总
Spring Boot解决跨域问题方法汇总
|
5天前
|
监控 Java 应用服务中间件
spring和springboot的区别
spring和springboot的区别
15 1
|
19天前
|
监控 测试技术 程序员
解决线程死循环问题的有效方法
作为开发者想必都清楚,多线程应用程序的开发为我们日常开发工作中提供了并发执行任务的能力,但线程死循环问题却是一个常见而令人头疼的挑战,因为线程死循环可能导致系统的不稳定性、资源浪费以及应用程序的异常运行,所以准确地定位和妥善处理线程死循环现象,并在编码阶段就避免潜在风险,成为开发人员必须面对的重要问题,线程死循环问题的解决不仅有助于提高系统的稳定性和可用性,还能优化资源利用和提升应用程序的性能,通过采取适当的预防和处理措施,开发人员能够避免线程陷入无尽的循环,并及时发现和解决潜在问题。那么本文就来分享一下关于如何处理线程死循环问题,以及如何在编码阶段规避潜在风险。
29 2
解决线程死循环问题的有效方法
|
29天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
271 0
|
2月前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
9 0
|
22天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
4天前
|
XML Java 数据格式
手写spring第七章-完成便捷实现bean对象初始化和销毁方法
手写spring第七章-完成便捷实现bean对象初始化和销毁方法
6 0
|
4天前
|
Java Maven Docker
0.07 秒启动一个 SpringBoot 项目!Spring Native 很强!!
0.07 秒启动一个 SpringBoot 项目!Spring Native 很强!!
17 2
|
6天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
9天前
|
NoSQL
线程死循环的定位方法
线程死循环的定位方法
17 2