spring或springBoot项目随项目启动而启动线程执行特定任务的方法
本帖最后由 fei888888 于 2023-8-2 10:43 编辑项目启动,你是否有需求需要某个任务能随着项目启动就去执行某个任务呢?代码如下
喜欢给点热心值{:1_893:}
当然方法不止一种 如注解:@PostConstruct 或者springBoot项目实现 ApplicationRunner
import com.gpyh.gms.server.service.goods.GoodsInfoSynchService;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
//@DependsOn({"需要依赖的类(启动的线程,需要在这个类后面完成初始化可添加)"})
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger logger = LoggerFactory.getLogger(MyApplicationListener.class);
@Autowired
private GoodsInfoSynchService goodsInfoSynchService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// 创建单线程池
ExecutorService executor = Executors.newSingleThreadExecutor();
logger.info("线程启动监控");
executor.execute(()->**需要执行的任务**);
}
}
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class QueueMonitor {
@PostConstruct
public void startQueueMonitor() {
Thread thread = new Thread(new YourQueueMonitorRunnable());
thread.start();
}
private class YourQueueMonitorRunnable implements Runnable {
@Override
public void run() {
// 监控队列的逻辑
}
}
} 谢谢分享~ 谢楼主的分享
页:
[1]