本帖最后由 fei888888 于 2023-8-2 10:43 编辑
项目启动,你是否有需求需要某个任务能随着项目启动就去执行某个任务呢?代码如下
喜欢给点热心值
当然方法不止一种 如注解:@PostConstruct 或者springBoot项目实现 ApplicationRunner
[Java] 纯文本查看 复制代码 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(()->**需要执行的任务**);
}
} |