zhang
2 天以前 14f2c4fce50c871d84f89d2dca2298e0892b4672
zy-acs-cv/src/main/java/com/zy/core/ConveyorBackgroundService.java
New file
@@ -0,0 +1,91 @@
package com.zy.core;
import com.zy.core.properties.CtuOperationConfig;
import com.zy.core.properties.CtuServiceProperties;
import com.zy.core.properties.SystemProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j
@Component
public class ConveyorBackgroundService {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private ConveyorOperationExecutor operationExecutor;
    @Autowired
    private CtuServiceProperties properties;
    private ScheduledExecutorService executorService;
    private final AtomicBoolean running = new AtomicBoolean(false);
    @PostConstruct
    public void init() {
        // 初始化线程池
        executorService = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setName("cv-background-thread");
            thread.setDaemon(true);
            return thread;
        });
        // 启动定时任务
        executorService.scheduleAtFixedRate(this::processConveyorTasks,
                properties.getInitialDelay(),
                properties.getInterval(),
                TimeUnit.MILLISECONDS);
        running.set(true);
        log.info("输送线后台服务线程初始化完成");
    }
    private void processConveyorTasks() {
        // 系统运行状态判断
        if (!SystemProperties.WCS_RUNNING_STATUS.get() || !running.get()) {
            log.debug("系统未运行或服务已停止,跳过输送线任务处理");
            return;
        }
        try {
            // 执行配置的操作序列
            for (CtuOperationConfig config : properties.getOperations()) {
                //log.info("执行输送线操作: {}", config.getType());
                operationExecutor.execute(config);
            }
            //log.info("输送线任务处理完成");
        } catch (Exception e) {
            log.error("输送线任务处理异常", e);
        }
    }
    @PreDestroy
    public void shutDown() {
        running.set(false);
        if (executorService != null && !executorService.isShutdown()) {
            log.info("正在关闭输送线后台服务线程...");
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
            log.info("输送线后台服务线程已关闭");
        }
    }
}