package com.bcxin.backend.tasks; import com.bcxin.backend.core.utils.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class TaskAbstract { protected static Logger logger = LoggerFactory.getLogger(TaskAbstract.class); private volatile boolean isRunning = false; public final void run() { if (isRunning) { logger.warn(String.format("任务(%s)正在执行中...", this.getClass().getName())); return; } isRunning = true; boolean isAllowedRun = false; try { isAllowedRun = beforeRun(); if (isAllowedRun) { this.log("开始执行"); runCore(); } else { this.log(String.format("任务beforeRun的返回结果为不可执行")); } } catch (Exception ex) { logger.error("{} 执行任务发生异常: {}", this.getClass().getName(), ExceptionUtils.getStackMessage(ex)); } finally { isRunning = false; afterRun(isAllowedRun); this.log("执行完毕"); } } protected boolean beforeRun() { return true; } protected void afterRun(boolean isAllowedRun) { try { Thread.sleep(2 * 1000); } catch (Exception ex) { ex.printStackTrace(); } } protected abstract void runCore() throws Exception; protected void log(String msg) { logger.error("err{}:{} 任务-{}:{}", Thread.currentThread().getId(), this.getClass().getName(), msg); } public abstract String getTaskName(); }