I am trying to schedule a task but the error window for missing the requested time is 1-2 seconds. Because of drift I wanted to check the time recursively and adjust it. I've run this code in short periods of time (max delay: 15 mins) and it worked very well. But the job will be scheduled for 8 to 12 hours from now in most of the cases.
public void scheduleTask(LocalDateTime localDateTime) {
long delay = ChronoUnit.MILLIS.between(LocalDateTime.now(),localDateTime);
if (delay < 30000) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(() -> myTask() ,delay, TimeUnit.MILLISECONDS);
}
else {
try {
Thread.sleep(delay/2);
} catch (InterruptedException ignored) {
}
scheduleTask(localDateTime);
}
}
I looked at various topics here but could not see a real solution. Mostly it is said that it is impossible to run a code in exact time because the schedulers operates based on delay and not on the given time.
Does calling the function recursively affect the computer in any aspect considering 8-12 hours period ? If yes, how should I overcome that ?