package com.inspect.job.task;

import com.inspect.base.core.enums.TaskStatus;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

public class StatusMonitor {
    private final Supplier<Integer> statusSupplier;

    private final AtomicInteger status = new AtomicInteger(Integer.parseInt(TaskStatus.RUNNING.getCode())); // 默认执行状态
    private final Thread monitorThread;
    private volatile boolean running = true;

    public StatusMonitor(Supplier<Integer> statusSupplier) {
        this.statusSupplier = statusSupplier;

        monitorThread = new Thread(() -> {
            while (running) {
                try {
                    int newStatus = this.statusSupplier.get();
                    status.set(newStatus);
                    Thread.sleep(1000); // 每1秒更新一次状态
                } catch (Exception e) {
                    e.printStackTrace(); // 可替换为日志
                }
            }
        }, "status-monitor-thread");

        monitorThread.setDaemon(true);
        monitorThread.start();
    }

    public int getStatus() {
        return status.get();
    }

    public void stop() {
        running = false;
        monitorThread.interrupt();
    }
}

