package com.xzzn.quartz.config;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Modbus操作执行器配置
 * 所有Modbus读写操作必须通过此单线程执行器串行执行，避免并发访问导致通讯故障
 */
@Configuration
public class ModbusExecutorConfig {

    private final ExecutorService modbusExecutor = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r, "modbus-io-thread");
        t.setDaemon(false);
        return t;
    });

    @Bean(name = "modbusExecutor")
    public ExecutorService modbusExecutor() {
        return modbusExecutor;
    }

    @PreDestroy
    public void shutdown() {
        modbusExecutor.shutdown();
    }
}
