package com.xzzn.quartz.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {


    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();

    public void startTask(String deviceId, Runnable task, long period) {
        stopTask(deviceId); // 如果已有同ID任务在运行，先停止
        ScheduledFuture<?> future = executor.scheduleAtFixedRate(task, 0, period, TimeUnit.MILLISECONDS);
        futureMap.put(deviceId, future);
    }

    public void stopTask(String deviceId) {
        ScheduledFuture<?> future = futureMap.get(deviceId);
        if (future != null && !future.isDone()) {
            future.cancel(true);
        }
        futureMap.remove(deviceId);
    }


}
