首页 > 解决方案 > 是否可以在spring boot/java中实现每个用户在不同时间动态调度一个任务

问题描述

我们有一个 REST API "/schedule" 用于安排对 3rd party 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 小时。因此,执行应该就像计划任务在不同的时间为不同的用户执行一样。

标签: javamultithreadingspring-bootscheduled-tasksquartz-scheduler

解决方案


将适当的时间传递给该scheduleAtFixedRate方法。

您的代码中已经有一个用于该目的的变量:time.

您将毫秒指定为时间单位。使用Duration类将分钟或小时转换为毫秒。

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 登录时,为他的用户对象运行相同的代码。

后来,Alice 想要更改时间量。rescheduleTaskForUser( Duration timeToWaitBetweenRunsForThisUser )在 Alice 的用户会话跟踪对象上调用另一个方法。该方法访问ScheduledFuture为 Alice 存储的对象,取消该未来,再次安排任务,并返回一个新ScheduledFuture对象以存储在 Alice 的用户会话跟踪对象上。


推荐阅读