Reputation: 21
Job: Need to invoke API periodically with time interval. Interval is determined from API only because API will return expireIn as a interval and We need to invoke the API again with that interval.
Purpose of Interval: Approaching API for the Token. And Token will be expired on particular timing. Expire timing will be also returned by API along with token. Need to invoke API for getting fresh token based on interval.
Approach tried & failed: Invoking API to get the response of token & expire timing as runnable task with ScheduledExecutorService in method of scheduleWithFixedDelay().
Approach failed: Unable to pass interval of expire of API response from runnable task to the method of scheduleWithFixedDelay(Runnable task, initialdelay, interval, Time unit);
From below code, I tried to declare variable interval as volatile to maintain single main memory. But can not pass it. scheduleWithFixedDelay() accpeting the initial value of volatile variable interval, not with the interval getting from API response method. Kindly help to achieve it. I tried with Thread.sleep() but unable to handle thread memory properly. Let me know if any other best approach for the job.
Code:
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleWithFixedDelay(
new Runnable() {
public void run() {
try {
interval = RestClient.getResponse();
} catch (Exception e) {
printErrorLog(e);
}
}
},
0,
interval,
TimeUnit.SECONDS);
Upvotes: 0
Views: 34
Reputation: 408
Your task is a Delayed Task, not a Periodic Task, which means it should be executed after some time, rather than being executed periodically. You should use schedule
instead of scheduleAtFixedRate
or scheduleWithFixedDelay
.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
Runnable freshTask = new Runnable() {
@Override
public void run() {
try {
long interval = RestClient.getResponse();
scheduledExecutorService.schedule(this, interval, TimeUnit.SECONDS);
} catch(Exception e) {
printErrorLog(e);
}
}
};
scheduledExecutorService.execute(freshTask); // initiate the chain
...
// remember to stop the loop
scheduledExecutorService.shutdown();
Upvotes: 1