java 定时任务报警器

import lombok.SneakyThrows;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author seven
 * @version 1.0
 * @description TODO
 * @date 2021/11/14 23:24
 */
public class AlarmTimeOut {

    private final CountTimeTask countTimeTask;

    private final ScheduledExecutorService scheduledExecutorService;



    public AlarmTimeOut() {
        this.countTimeTask = new AlarmTimeOut.CountTimeTask();
        this.scheduledExecutorService = Executors.newScheduledThreadPool(1);
    }

    public void start() {
        scheduledExecutorService.scheduleAtFixedRate(countTimeTask, 0, 1, TimeUnit.SECONDS);
    }

    public void stop() {
        this.scheduledExecutorService.shutdownNow();
        this.countTimeTask.executorService.shutdownNow();
    }

    /**
     * 添加任务
     *
     * @param taskName 任务名
     * @param timeout  超时时间 单位秒
     * @return
     */
    public AlarmTimeOut addTask(String taskName, int timeout) {
        this.addTask(taskName, timeout, null);
        return this;
    }

    /**
     * 添加任务
     *
     * @param taskName 任务名
     * @param timeout  超时时间 单位秒
     * @param event    执行的事件
     * @return
     */
    public AlarmTimeOut addTask(String taskName, int timeout, Runnable event) {
        AlarmTimeOut.TaskInfo taskInfo = new AlarmTimeOut.TaskInfo(System.currentTimeMillis(), timeout, event);
        if (null != this.countTimeTask.get(taskName)) {
            throw new IllegalStateException("task is already exist");
        }
        this.countTimeTask.put(taskName, taskInfo);
        return this;
    }

    /**
     * 获取任务的剩余时间 单位毫秒
     *
     * @param taskName
     * @return 单位 ms
     */
    public long getTaskTimeLeft(String taskName) {
        AlarmTimeOut.TaskInfo taskInfo = this.countTimeTask.get(taskName);
        if (null == taskInfo) {
            throw new IllegalStateException("task is not exist");
        }
        return taskInfo.getAlertTime() - taskInfo.getStartTime();

    }

    public static final class CountTimeTask implements Runnable {

        private final Map<String, TaskInfo> taskMap;
        private final ExecutorService executorService;

        public CountTimeTask() {
            this.taskMap = new ConcurrentHashMap<>(8);
            this.executorService = Executors.newFixedThreadPool(1);

        }

        public TaskInfo get(String taskName) {
            return this.taskMap.get(taskName);
        }

        public CountTimeTask put(String taskName, TaskInfo taskInfo) {
            this.taskMap.put(taskName, taskInfo);
            return this;
        }

        @Override
        public void run() {
            long current = System.currentTimeMillis();
            System.out.println("exec time -> " + current);
            this.taskMap.forEach((k, v) -> {
                if (current > v.getAlertTime()) {
                    System.out.println(k + "is already exist");
                    if (null != v.getEvent()) {
                        this.executorService.execute(v.getEvent());
                    }
                    this.taskMap.remove(k);
                }
            });
        }
    }

    public static final class TaskInfo {
        //启动时间 ms
        private final long startTime;
        //超时时常 ms
        private final long alertTime;

        private final Runnable event;

        TaskInfo(long startTime, int timeout, Runnable event) {
            this.startTime = startTime;
            this.alertTime = startTime + timeout * 1000;
            this.event = event;
        }

        public long getStartTime() {
            return startTime;
        }

        public long getAlertTime() {
            return alertTime;
        }

        public Runnable getEvent() {
            return event;
        }

        @Override
        public String toString() {
            return "TaskInfo{" +
                    "startTime=" + startTime +
                    ", alertTime=" + alertTime +
                    '}';
        }
    }
    @SneakyThrows
    public static void main(String[] args) {
        System.out.println("main time:" + System.currentTimeMillis());
        AlarmTimeOut ato = new AlarmTimeOut();
        ato.addTask("task 1 ", 6);
        ato.addTask("task 2 ", 5, new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                System.out.println("task 2 超时了!!!!!,我再休息3秒");
                Thread.sleep(3000);
                System.out.println("task 2 超时了!!!!!,我休息好了");
            }
        });
        ato.addTask("task 3 ", 7);
        ato.start();
        ato.countTimeTask.taskMap.forEach((k, v) -> {
            System.out.println(v);
        });
        Thread.sleep(10000);
        System.out.println("main time:" + System.currentTimeMillis());
        ato.stop();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值