Pārlūkot izejas kodu

定时任务支持 FixedRate、 FixedDelay 两种

sunyj 8 gadi atpakaļ
vecāks
revīzija
20b28d3471

+ 4 - 4
src/main/java/com/uas/search/controller/IndexController.java

@@ -68,8 +68,8 @@ public class IndexController {
 
 	@RequestMapping("/listen/start")
 	@ResponseBody
-	public String startListen(Long period, HttpServletRequest request) {
-		jmsListener.start(period);
+	public String startListen(Long interval, HttpServletRequest request) {
+		jmsListener.start(interval);
         return "开启成功";
 	}
 
@@ -82,11 +82,11 @@ public class IndexController {
 
 	@RequestMapping("/listen/restart")
 	@ResponseBody
-	public String restartListen(Long period, HttpServletRequest request) {
+	public String restartListen(Long interval, HttpServletRequest request) {
 		if (jmsListener.isRunning()) {
 			jmsListener.stop();
 		}
-		jmsListener.start(period);
+		jmsListener.start(interval);
         return "重启成功";
 	}
 

+ 9 - 9
src/main/java/com/uas/search/jms/JmsListener.java

@@ -29,7 +29,7 @@ public class JmsListener {
     /**
      * 两次任务之间的等待时间间隔为 1 秒钟
      */
-    private static final long PERIOD = 1000;
+    private static final long INTERVAL = 1000;
 
     @Autowired
     private LuceneMessageDao luceneMessageDao;
@@ -53,18 +53,18 @@ public class JmsListener {
     /**
      * 开启实时更新索引
      *
-     * @param period
+     * @param interval
      *            每次接收到jms消息后等待的时间(秒)
      * @return 开启成功与否的提示信息
      */
-    public void start(Long period) {
-        if(period == null){
-            period = PERIOD;
+    public void start(Long interval) {
+        if(interval == null){
+            interval = INTERVAL;
         }else{
-            period *= 1000;
+            interval *= 1000;
         }
-        if(period <= 0){
-            throw new IllegalArgumentException("period 不合法:" + period);
+        if(interval <= 0){
+            throw new IllegalArgumentException("interval 不合法:" + interval);
         }
 
         if (isRunning()) {
@@ -95,7 +95,7 @@ public class JmsListener {
                     return "正常";
                 }
             };
-            taskInformation = new TaskInformation(title, command, INITIAL_DELAY, period);
+            taskInformation = new TaskInformation(title, command, INITIAL_DELAY, interval, TaskInformation.ScheduleType.FixedDelay);
             taskService.newTask(taskInformation);
             if (!taskService.isStopped()) {
                 taskService.stop();

+ 50 - 9
src/main/java/com/uas/search/schedule/TaskInformation.java

@@ -35,18 +35,21 @@ public class TaskInformation {
 	/**
 	 * 两次任务之间的等待时间间隔(毫秒)
 	 */
-	private long period;
+	private long interval;
+
+	private ScheduleType scheduleType;
 
 	public TaskInformation() {
 		super();
 	}
 
-	public TaskInformation(String title, Executable command, long initialDelay, long period) {
+	public TaskInformation(String title, Executable command, long initialDelay, long interval, ScheduleType scheduleType) {
 		init();
 		this.title = title;
 		this.command = command;
 		this.initialDelay = initialDelay;
-		this.period = period;
+		this.interval = interval;
+		this.scheduleType = scheduleType;
 	}
 
 	public void init(){
@@ -85,12 +88,20 @@ public class TaskInformation {
 		this.initialDelay = initialDelay;
 	}
 
-	public long getPeriod() {
-		return period;
+	public long getInterval() {
+		return interval;
+	}
+
+	public void setInterval(long interval) {
+		this.interval = interval;
+	}
+
+	public ScheduleType getScheduleType() {
+		return scheduleType;
 	}
 
-	public void setPeriod(long period) {
-		this.period = period;
+	public void setScheduleType(ScheduleType scheduleType) {
+		this.scheduleType = scheduleType;
 	}
 
 	@Override
@@ -104,12 +115,42 @@ public class TaskInformation {
 		TaskInformation other = (TaskInformation) obj;
 		// command不好比较,不进行比较,也不比较 code
 		return Objects.equals(title, other.getTitle()) && initialDelay == other.getInitialDelay()
-				&& period == other.getPeriod();
+				&& interval == other.getInterval() && scheduleType == other.getScheduleType();
 	}
 
 	@Override
 	public String toString() {
-		return "TaskInformation [code=" + code + ", title=" + title + ", initialDelay=" + initialDelay + ", period=" + period + "]";
+		return "TaskInformation [code=" + code + ", title=" + title + ", initialDelay=" + initialDelay + ", interval=" + interval + ", scheduleType=" + scheduleType + "]";
 	}
 
+	/**
+	 * 定时的间隔类型
+	 */
+	public enum ScheduleType {
+		/**
+		 * Creates and executes a periodic action that becomes enabled first
+		 * after the given initial delay, and subsequently with the given
+		 * period; that is executions will commence after
+		 * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
+		 * <tt>initialDelay + 2 * period</tt>, and so on.
+		 * If any execution of the task
+		 * encounters an exception, subsequent executions are suppressed.
+		 * Otherwise, the task will only terminate via cancellation or
+		 * termination of the executor.  If any execution of this task
+		 * takes longer than its period, then subsequent executions
+		 * may start late, but will not concurrently execute.
+		 */
+		FixedRate,
+
+		/**
+		 * Creates and executes a periodic action that becomes enabled first
+		 * after the given initial delay, and subsequently with the
+		 * given delay between the termination of one execution and the
+		 * commencement of the next.  If any execution of the task
+		 * encounters an exception, subsequent executions are suppressed.
+		 * Otherwise, the task will only terminate via cancellation or
+		 * termination of the executor.
+		 */
+		FixedDelay
+	}
 }

+ 10 - 2
src/main/java/com/uas/search/schedule/TaskServiceImpl.java

@@ -142,8 +142,16 @@ public class TaskServiceImpl implements TaskService {
 			scheduledExecutorService = Executors.newScheduledThreadPool(1);
 			for (TaskInformation taskInformation : taskInformations) {
 				logger.info("New task: " + taskInformation);
-				scheduledExecutorService.scheduleAtFixedRate(getCommand(taskInformation),
-						taskInformation.getInitialDelay(), taskInformation.getPeriod(), TimeUnit.MILLISECONDS);
+				switch (taskInformation.getScheduleType()){
+                    case FixedRate:
+                        scheduledExecutorService.scheduleAtFixedRate(getCommand(taskInformation),
+                                taskInformation.getInitialDelay(), taskInformation.getInterval(), TimeUnit.MILLISECONDS);
+                        break;
+                    case FixedDelay:
+                        scheduledExecutorService.scheduleWithFixedDelay(getCommand(taskInformation),
+                                taskInformation.getInitialDelay(), taskInformation.getInterval(), TimeUnit.MILLISECONDS);
+                        break;
+                }
 			}
 			message = "已开启定时任务:" + taskInformations;
 			logger.info(message + "\n");

+ 2 - 2
src/main/java/com/uas/search/service/impl/RealTimeUpdateMonitorServiceImpl.java

@@ -32,7 +32,7 @@ public class RealTimeUpdateMonitorServiceImpl implements RealTimeUpdateMonitorSe
     /**
      * 两次任务之间的等待时间间隔为5分钟
      */
-    private static final long PERIOD = 5 * 60 * 1000;
+    private static final long INTERVAL = 5 * 60 * 1000;
     @Autowired
     private TaskService taskService;
 
@@ -71,7 +71,7 @@ public class RealTimeUpdateMonitorServiceImpl implements RealTimeUpdateMonitorSe
                 return "正常";
             }
         };
-        TaskInformation taskInformation = new TaskInformation(title, command, INITIAL_DELAY, PERIOD);
+        TaskInformation taskInformation = new TaskInformation(title, command, INITIAL_DELAY, INTERVAL, TaskInformation.ScheduleType.FixedDelay);
         taskService.newTask(taskInformation);
         return taskInformation;
     }

+ 1 - 1
src/main/webapp/WEB-INF/views/console.html

@@ -84,7 +84,7 @@
 				<li><a target="_blank">index/create</a></li>
 				<li><a target="_blank">index/create?tableNames=product$brand,trade$order</a></li>
 				<li><a target="_blank">index/downloadComponentData?startFileIndex=20</a></li>
-				<li><a target="_blank">index/listen/start?period=10</a></li>
+				<li><a target="_blank">index/listen/start?interval=10</a></li>
 				<li><a target="_blank">index/listen/stop</a></li>
 				<li><a target="_blank">index/listen/restart</a></li>
 				<li><a target="_blank">index/listen/details?page=1&size=10</a></li>