繁体   English   中英

是否可以在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);

但这不是实际要求。 让我们通过一个例子来理解需求。 示例&要求: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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM