SmartReloadScheduler.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package net.lab1024.smartadmin.common.reload;
  2. import net.lab1024.smartadmin.common.reload.interfaces.SmartReloadCommandInterface;
  3. import net.lab1024.smartadmin.common.reload.interfaces.SmartReloadThreadLogger;
  4. import java.util.concurrent.ScheduledThreadPoolExecutor;
  5. import java.util.concurrent.ThreadFactory;
  6. import java.util.concurrent.TimeUnit;
  7. import java.util.concurrent.atomic.AtomicInteger;
  8. /**
  9. * Reload 调度器
  10. *
  11. * @author zhuoda
  12. */
  13. public class SmartReloadScheduler {
  14. private ScheduledThreadPoolExecutor executor;
  15. private SmartReloadThreadLogger logger;
  16. SmartReloadScheduler(SmartReloadThreadLogger logger, int threadCount) {
  17. this.executor = new ScheduledThreadPoolExecutor(threadCount, new SmartReloadSchedulerThreadFactory());
  18. this.logger = logger;
  19. }
  20. void shutdown() {
  21. try {
  22. executor.shutdown();
  23. } catch (Throwable e) {
  24. logger.error("<<SmartReloadScheduler>> shutdown ", e);
  25. }
  26. }
  27. void addCommand(SmartReloadCommandInterface command, long initialDelay, long delay, TimeUnit unit) {
  28. executor.scheduleWithFixedDelay(new ScheduleRunnable(command, this.logger), initialDelay, delay, unit);
  29. }
  30. static class ScheduleRunnable implements Runnable {
  31. private SmartReloadCommandInterface command;
  32. private SmartReloadThreadLogger logger;
  33. public ScheduleRunnable(SmartReloadCommandInterface command, SmartReloadThreadLogger logger) {
  34. this.command = command;
  35. this.logger = logger;
  36. }
  37. @Override
  38. public void run() {
  39. try {
  40. command.doTask();
  41. } catch (Throwable e) {
  42. logger.error("", e);
  43. }
  44. }
  45. }
  46. static class SmartReloadSchedulerThreadFactory implements ThreadFactory {
  47. private static final AtomicInteger poolNumber = new AtomicInteger(1);
  48. private final ThreadGroup group;
  49. private final AtomicInteger threadNumber = new AtomicInteger(1);
  50. private final String namePrefix;
  51. SmartReloadSchedulerThreadFactory() {
  52. SecurityManager s = System.getSecurityManager();
  53. group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
  54. namePrefix = "smartreload-" + poolNumber.getAndIncrement() + "-thread-";
  55. }
  56. @Override
  57. public Thread newThread(Runnable r) {
  58. Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
  59. if (t.isDaemon())
  60. t.setDaemon(false);
  61. if (t.getPriority() != Thread.NORM_PRIORITY)
  62. t.setPriority(Thread.NORM_PRIORITY);
  63. return t;
  64. }
  65. }
  66. }