spring boot/java 是否可以在不同时间为每个用户实现任务的动态调度

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);

但这不是实际要求。让我们通过一个例子来理解需求。 示例&要求:用户1登录并在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 ; 
}

爱丽丝登录并说她想要 5 分钟的时间。

String input = … ;  // For example, "PT5M".
Duration d = Duration.parse( input ) ;
ScheduledFuture sf = scheduleTaskForUser( d ) ;
user.setScheduledFuture( sf ) ; 

当 Bob 登录时,运行 为他的用户对象使用相同的代码。

稍后,爱丽丝想要更改时间量。在 Alice 的用户会话跟踪对象上调用另一个方法 rescheduleTaskForUser( Duration timeToWaitBetweenRunsForThisUser )。该方法为 Alice 访问存储的 ScheduledFuture 对象,取消该 future,再次安排任务,然后 returns 一个新的 ScheduledFuture 对象存储在 Alice 的用户会话跟踪对象上。