DynamicTask.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.genersoft.iot.vmp.conf;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
  5. import org.springframework.stereotype.Component;
  6. import java.util.Date;
  7. import java.util.Map;
  8. import java.util.concurrent.ConcurrentHashMap;
  9. import java.util.concurrent.ScheduledFuture;
  10. /**
  11. * 动态定时任务
  12. */
  13. @Component
  14. public class DynamicTask {
  15. @Autowired
  16. private ThreadPoolTaskScheduler threadPoolTaskScheduler;
  17. private Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
  18. @Bean
  19. public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
  20. return new ThreadPoolTaskScheduler();
  21. }
  22. /**
  23. * 循环执行的任务
  24. * @param key 任务ID
  25. * @param task 任务
  26. * @param cycleForCatalog 间隔
  27. * @return
  28. */
  29. public String startCron(String key, Runnable task, int cycleForCatalog) {
  30. stop(key);
  31. // scheduleWithFixedDelay 必须等待上一个任务结束才开始计时period, cycleForCatalog表示执行的间隔
  32. ScheduledFuture future = threadPoolTaskScheduler.scheduleWithFixedDelay(task, cycleForCatalog * 1000L);
  33. futureMap.put(key, future);
  34. return "startCron";
  35. }
  36. /**
  37. * 延时任务
  38. * @param key 任务ID
  39. * @param task 任务
  40. * @param delay 延时 /秒
  41. * @return
  42. */
  43. public String startDelay(String key, Runnable task, int delay) {
  44. stop(key);
  45. Date starTime = new Date(System.currentTimeMillis() + delay * 1000);
  46. // scheduleWithFixedDelay 必须等待上一个任务结束才开始计时period, cycleForCatalog表示执行的间隔
  47. ScheduledFuture future = threadPoolTaskScheduler.schedule(task, starTime);
  48. futureMap.put(key, future);
  49. return "startCron";
  50. }
  51. public void stop(String key) {
  52. if (futureMap.get(key) != null && !futureMap.get(key).isCancelled()) {
  53. futureMap.get(key).cancel(true);
  54. }
  55. }
  56. public boolean contains(String key) {
  57. return futureMap.get(key) != null;
  58. }
  59. }