package cn.com.qmth.examcloud.commons.helpers; import java.io.File; import cn.com.qmth.examcloud.commons.logging.ExamCloudLog; import cn.com.qmth.examcloud.commons.logging.ExamCloudLogFactory; /** * 文件变更监视器 * * @author WANGWEI */ public abstract class FileChangeWatchdog extends Thread { /** * 属性注释 */ private static final ExamCloudLog LOG = ExamCloudLogFactory.getLog(FileChangeWatchdog.class); /** * 属性注释 */ static final public long DEFAULT_DELAY = 60000; /** * 属性注释 */ protected String path; /** * 属性注释 */ protected long delay = DEFAULT_DELAY; /** * 属性注释 */ protected File file; /** * 属性注释 */ protected long lastModif = 0; /** * 属性注释 */ protected boolean warnedAlready = false; /** * 属性注释 */ protected boolean interrupted = false; /** * 构造函数 * * @param path */ protected FileChangeWatchdog(String path) { super("FileChangeWatchdog"); LOG.info("new a FileChangeWatchdog. path=" + path); this.path = path; file = new File(path); setDaemon(true); checkAndConfigure(); } /** * 方法注释 * * @author WANGWEI * @param delay */ public void setDelay(long delay) { this.delay = delay; } /** * 方法注释 * * @author WANGWEI */ abstract protected void doOnChange(); /** * 方法注释 * * @author WANGWEI */ protected void checkAndConfigure() { boolean fileExists; try { fileExists = file.exists(); } catch (SecurityException e) { LOG.warn("Was not allowed to read check file existance, file:[" + path + "]."); interrupted = true; return; } if (fileExists) { long l = file.lastModified(); if (l > lastModif) { lastModif = l; doOnChange(); warnedAlready = false; } } else { if (!warnedAlready) { LOG.debug("[" + path + "] does not exist."); warnedAlready = true; } } } /* * 实现 * * @author WANGWEI * * @see java.lang.Thread#run() */ @Override public void run() { while (!interrupted) { try { Thread.sleep(delay); } catch (InterruptedException e) { LOG.error("unexpected interruption.", e); } checkAndConfigure(); } } }