package com.ynxbd.common.helper.timer; import lombok.extern.slf4j.Slf4j; import java.util.Timer; import java.util.TimerTask; @Slf4j public abstract class TimerManager extends TimerTask { public abstract static class TimerMethod { public abstract void run() throws Exception; } /** * @param timerMethod 执行器 * @param second 间隔(s) */ public static synchronized Timer setInterval(TimerMethod timerMethod, int second) { try { if (second == 0) { throw new Exception("周期间隔不能为0s"); } long periodSecond = second * 1000L; Timer timer = new Timer(); timer.schedule(new TimerManager() { @Override public synchronized void run() { try { long begTime = System.currentTimeMillis(); // 开始时间 timerMethod.run(); long endTime = System.currentTimeMillis(); // 结束时间 long runTime = (endTime - begTime); // 耗时 if (runTime > periodSecond) { Thread.sleep(periodSecond); } else if (runTime > (periodSecond / 2)) { Thread.sleep((periodSecond / 2)); } log.info("[定时器]执行耗时:" + runTime + "ms"); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); try { Thread.sleep(periodSecond); } catch (Exception exception) { exception.printStackTrace(); } } } }, 0, periodSecond); return timer; } catch (Exception e) { e.printStackTrace(); } return null; } public synchronized static void closeTimer(Timer timer) { timer.cancel(); } }