[英]is it possible to achieve dynamic scheduling of a task for each user at different time in spring boot/java
我們有一個 REST API "/schedule" 用於安排對第 3 方 API 的調用。 當一個用戶登錄並將他的調度器時間設置為 1 分鍾的任務時,它會為每個用戶設置(使用方法名稱為 scheduleAtFixedRate 的 shceduledExecutorService)
TaskUtils mytask1 = new TaskUtils(this);
scheduledExecutorService = Executors.newScheduledThreadPool(1);
futureTask = scheduledExecutorService.scheduleAtFixedRate(mytask1, 0, time, TimeUnit.MILLISECONDS);
但這不是實際要求。 讓我們通過一個例子來理解需求。 示例&要求:user1 登錄並安排一個任務,時間差為 1 分鍾。 當 user2 登錄時,他想將任務安排在 1 小時。 因此,執行應該就像計划任務在不同的時間為不同的用戶執行一樣。
將適當的時間傳遞給scheduleAtFixedRate
方法。
您已經在代碼中顯示了一個用於該目的的變量: time
。
您將毫秒指定為時間單位。 使用Duration
class 將分鍾或小時轉換為毫秒。
long time = Duration.ofMinutes( 1 ).toMillis() ;
或者從幾小時到幾毫秒。
long time = Duration.ofHours( 1 ).toMillis() ;
或使用標准ISO 8601表示法指定的任意時間量。 這是一個又一刻鍾。
long time = Duration.parse( "PT1H15M" ).toMillis() ;
在某處設置您的執行器服務。
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
在某處設置您的任務。
Task task = new TaskUtils(this);
…
編寫一個為每個新用戶調用的方法。
FutureTask scheduleTaskForUser ( Duration timeToWaitBetweenRunsForThisUser ) {
ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleAtFixedRate( task , 0 , timeToWaitBetweenRunsForThisUser.toMillis() , TimeUnit.MILLISECONDS );
return scheduledFuture ;
}
Alice 登錄並說她想要 5 分鍾的時間。
String input = … ; // For example, "PT5M".
Duration d = Duration.parse( input ) ;
ScheduledFuture sf = scheduleTaskForUser( d ) ;
user.setScheduledFuture( sf ) ;
Bob 登錄后,為他的用戶 object 運行相同的代碼。
后來,Alice 想要更改時間量。 在用戶會話跟蹤 object 上為 Alice 調用另一個方法rescheduleTaskForUser( Duration timeToWaitBetweenRunsForThisUser )
。 該方法為 Alice 訪問存儲的ScheduledFuture
object,取消該未來,再次安排任務,並返回一個新的ScheduledFuture
object 以存儲在用戶會話跟蹤 ZA8CFDE6331BD59EB2AC96F8911C4B6 上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.