package com.walker.infrastructure.scheduler; import com.walker.infrastructure.core.NestedRuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 抽象定时任务定义基类,子类实现具体执行任务,同时可以设置间隔时间和延时时间 * @author MikeShi * */ public abstract class AbstractTimedTask implements TimedTask { protected transient Logger logger = LoggerFactory.getLogger(this.getClass()); //最小间隔时间,默认5秒 private static final long TIMED_MIN_PERIOD = 5000; //最小延时时间,即系统启动后多长时间后开始运行任务,默认30秒钟 private static final long TIMED_MIN_DELAY = 30000; private static final int MAX_ERROR_COUNT = 10; private int errorCount = 0; private long delay = 5000; private long period = 0; public long getDelay() { // TODO Auto-generated method stub if(delay == 0){ delay = TIMED_MIN_DELAY; } return delay; } public long getPeriod() { // TODO Auto-generated method stub if(period < 0){ throw new NullPointerException("period must be set in TimedTask! It is more than 0."); } else if(period > 0 && period < TIMED_MIN_PERIOD){ throw new NestedRuntimeException("period must more than" + TIMED_MIN_PERIOD/1000 + " seconds in TimedTask!"); } return period; } public void setDelay(long delays) { // TODO Auto-generated method stub if(delays < TIMED_MIN_DELAY){ this.delay = TIMED_MIN_DELAY; } else this.delay = delays; } public void setPeriod(long periods) { // TODO Auto-generated method stub if(periods > 0 && periods < TIMED_MIN_PERIOD){ this.period = TIMED_MIN_PERIOD; } else this.period = periods; } public void run() { // TODO Auto-generated method stub if(period == 0){ logger.debug("任务执行忽略,设置间隔为0"); return; } if(errorCount > MAX_ERROR_COUNT){ //执行通知事件:告知管理员系统定时任务错误执行了最大值 //eventPublisher.notify(); logger.debug("//*************定时任务执行错误,已超出错误最大值!"); } try { execute(); } catch (Exception e) { // TODO Auto-generated catch block logger.warn("execute error in TimedTask: " + this.getClass().getName()); logger.error(e.getMessage()); errorCount++; } } public abstract void execute() throws Exception; }