FileChangeWatchdog.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package cn.com.qmth.examcloud.commons.helpers;
  2. import java.io.File;
  3. import cn.com.qmth.examcloud.commons.logging.ExamCloudLog;
  4. import cn.com.qmth.examcloud.commons.logging.ExamCloudLogFactory;
  5. /**
  6. * 文件变更监视器
  7. *
  8. * @author WANGWEI
  9. */
  10. public abstract class FileChangeWatchdog extends Thread {
  11. /**
  12. * 属性注释
  13. */
  14. private static final ExamCloudLog LOG = ExamCloudLogFactory.getLog(FileChangeWatchdog.class);
  15. /**
  16. * 属性注释
  17. */
  18. static final public long DEFAULT_DELAY = 60000;
  19. /**
  20. * 属性注释
  21. */
  22. protected String path;
  23. /**
  24. * 属性注释
  25. */
  26. protected long delay = DEFAULT_DELAY;
  27. /**
  28. * 属性注释
  29. */
  30. protected File file;
  31. /**
  32. * 属性注释
  33. */
  34. protected long lastModif = 0;
  35. /**
  36. * 属性注释
  37. */
  38. protected boolean warnedAlready = false;
  39. /**
  40. * 属性注释
  41. */
  42. protected boolean interrupted = false;
  43. /**
  44. * 构造函数
  45. *
  46. * @param path
  47. */
  48. protected FileChangeWatchdog(String path) {
  49. super("FileChangeWatchdog");
  50. LOG.info("new a FileChangeWatchdog. path=" + path);
  51. this.path = path;
  52. file = new File(path);
  53. setDaemon(true);
  54. checkAndConfigure();
  55. }
  56. /**
  57. * 方法注释
  58. *
  59. * @author WANGWEI
  60. * @param delay
  61. */
  62. public void setDelay(long delay) {
  63. this.delay = delay;
  64. }
  65. /**
  66. * 方法注释
  67. *
  68. * @author WANGWEI
  69. */
  70. abstract protected void doOnChange();
  71. /**
  72. * 方法注释
  73. *
  74. * @author WANGWEI
  75. */
  76. protected void checkAndConfigure() {
  77. boolean fileExists;
  78. try {
  79. fileExists = file.exists();
  80. } catch (SecurityException e) {
  81. LOG.warn("Was not allowed to read check file existance, file:[" + path + "].");
  82. interrupted = true;
  83. return;
  84. }
  85. if (fileExists) {
  86. long l = file.lastModified();
  87. if (l > lastModif) {
  88. lastModif = l;
  89. doOnChange();
  90. warnedAlready = false;
  91. }
  92. } else {
  93. if (!warnedAlready) {
  94. LOG.debug("[" + path + "] does not exist.");
  95. warnedAlready = true;
  96. }
  97. }
  98. }
  99. /*
  100. * 实现
  101. *
  102. * @author WANGWEI
  103. *
  104. * @see java.lang.Thread#run()
  105. */
  106. @Override
  107. public void run() {
  108. while (!interrupted) {
  109. try {
  110. Thread.sleep(delay);
  111. } catch (InterruptedException e) {
  112. LOG.error("unexpected interruption.", e);
  113. }
  114. checkAndConfigure();
  115. }
  116. }
  117. }