2016-07-25 78 views
1

我想以這種方式安排我的工作: 1)只有一個線程運行它。 (系列) 2)在兩次運行之間有固定間隔Spring @Scheduled fixedDelay無法正常工作

我在我的方法上面使用@Scheduled(fixedDelay = 10000),在我的applicationContext.xml中使用<task:annotation-driven/>。但根據我的印刷資料,兩個作業之間的間隔不是我設定的10000毫秒。這是爲什麼?

19:07-25 22:38:46.190 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457526190 
20:07-25 22:38:48.191 INFO schedule:45 [21-thread-1] - [job#1] use 2000ms 
21:07-25 22:38:48.191 INFO schedule:47 [21-thread-1] - [job#1] is finished. -----> 1469457528191 
25:07-25 22:39:03.198 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457543198 
26:07-25 22:39:05.201 INFO schedule:45 [21-thread-1] - [job#1] use 2002ms 
27:07-25 22:39:05.202 INFO schedule:47 [21-thread-1] - [job#1] is finished. -----> 1469457545202 
31:07-25 22:39:20.205 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457560205 
32:07-25 22:39:22.209 INFO schedule:45 [21-thread-1] - [job#1] use 2004ms 
33:07-25 22:39:22.210 INFO schedule:47 [21-thread-1] - [job#1] is finished. -----> 1469457562210 
37:07-25 22:39:37.213 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457577213 
38:07-25 22:39:39.215 INFO schedule:45 [21-thread-1] - [job#1] use 2002ms 
39:07-25 22:39:39.215 INFO schedule:47 [21-thread-1] - [job#1] is finished. -----> 1469457579215 
43:07-25 22:39:54.221 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457594221 
44:07-25 22:39:56.225 INFO schedule:45 [21-thread-1] - [job#1] use 2004ms 
45:07-25 22:39:56.225 INFO schedule:47 [21-thread-1] - [job#1] is finished. -----> 1469457596225 
49:07-25 22:40:11.525 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457611525 
50:07-25 22:40:13.528 INFO schedule:45 [21-thread-1] - [job#1] use 2003ms 
51:07-25 22:40:13.529 INFO schedule:47 [21-thread-1] - [job#1] is finished. -----> 1469457613529 
55:07-25 22:40:28.237 INFO schedule:33 [21-thread-1] - [job#1] is running. -----> 1469457628237 

你可以看到完成和運行之間的時間不是10000ms。 (更像15000)

的代碼是(春季4.2.1):

@Scheduled(fixedDelay = 10000) 
    public void timerJob1(){ 
     SCHEDULER.info("[job#1] is running. -----> {}", System.currentTimeMillis()); 
     Stopwatch stopwatch = Stopwatch.createStarted(); 

     try { 
      Thread.sleep(2000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
      long use = stopwatch.elapsed(TimeUnit.MILLISECONDS); 
      SCHEDULER.info("[timeJob1] use {}ms", use); 
     } 

     long use = stopwatch.elapsed(TimeUnit.MILLISECONDS); 
     SCHEDULER.info("[job#1] use {}ms", use); 

     SCHEDULER.info("[job#1] is finished. -----> {}", System.currentTimeMillis()); 
    } 

回答

0

您可能對線程池爭被使用。創建自己的執行程序,通過實現和連接ScheduledConfigr來處理這些固定的延遲任務。

在您的configureTasks()實現中,將您自己的Executor設置爲方法參數ScheduledTaskRegistrar上的調度程序。