简体   繁体   中英

is it possible to achieve dynamic scheduling of a task for each user at different time in spring boot/java

We have an REST API "/schedule" for scheduling a call to 3rd party API. when one User login and set his scheduler time to 1 minute for a task then it is set for every user (using shceduledExecutorService with method name scheduleAtFixedRate)

TaskUtils mytask1 = new TaskUtils(this);

            scheduledExecutorService = Executors.newScheduledThreadPool(1);

            futureTask = scheduledExecutorService.scheduleAtFixedRate(mytask1, 0, time, TimeUnit.MILLISECONDS);

but this is not the actual requirement. Let's understand the requirement with an example. Example & Requirement: user1 login and schedule a task at a time difference of 1 minute. when user2 login he want to scheduler the task at 1 hour. So, execution should be like that the scheduled task execute at different time for different users.

Pass the appropriate amount of time to the scheduleAtFixedRate method.

You already have a variable for that purpose shown in your code: time .

You are specifying milliseconds as your unit of time. Use Duration class to convert from minutes or hours to milliseconds.

long time = Duration.ofMinutes( 1 ).toMillis() ;

Or from hours to milliseconds.

long time = Duration.ofHours( 1 ).toMillis() ;

Or any arbitrary amount of time specified using standard ISO 8601 notation. Here is one and a quarter hours.

long time = Duration.parse( "PT1H15M" ).toMillis() ;

Set up your executor service somewhere.

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

Set up your task somewhere.

Task task = new TaskUtils(this);
…

Write a method to be called for each new user.

FutureTask scheduleTaskForUser ( Duration timeToWaitBetweenRunsForThisUser ) {
    ScheduledFuture scheduledFuture = scheduledExecutorService.scheduleAtFixedRate( task , 0 , timeToWaitBetweenRunsForThisUser.toMillis() , TimeUnit.MILLISECONDS );
    return scheduledFuture ; 
}

Alice logs in and says she wants a 5 minute period.

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

When Bob logs in, run the same code for his user object.

Later, Alice wants to change the amount of time. Call another method, rescheduleTaskForUser( Duration timeToWaitBetweenRunsForThisUser ) on the user-session tracking object for Alice. That method accesses the stored ScheduledFuture object for Alice, cancels that future, schedules the task again, and returns a new ScheduledFuture object to be stored on the user-session tracking object for Alice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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