java - 是否可以在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 小时。因此,执行应该就像计划任务在不同的时间为不同的用户执行一样。
解决方案
将适当的时间传递给该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 的用户会话跟踪对象上。
推荐阅读
- java - 如何使用java和eclipse在给定范围内随机生成敌人
- git - Git 流程 - 错误:无法创建功能分支
- opencart - 如何在 opencart 版本 3.0.3.2 中删除结帐字段
- javascript - 如何计算不同函数的值
- javascript - 在 Google 应用脚本中使用 jquery AJAX Post 方法
- java - Java 找不到资源文件
- android - 如何部署基于机器学习的 Android 应用程序?
- batch-file - 如何重命名/重新排列 Windows 批处理文件中的文件名格式以每小时运行一次
- rest - Xamarin 表单 - 无法从 REST API 获取对象到 xaml 页面
- c# - 即使没有 ModelState.IsValid netcore3,模型验证也能正常工作