When I use a ScheduledExecutor with TimeUnit.MINUTES and a value of 3, the task runs with delays of 3 minutes to 3 minutes and 10 seconds. Yes, I use scheduleWithFixedDelay (), but the job should only take a few milliseconds.
I did not find a clear indication from the java.util.concurrent documentation that TimeUnit.MINUTES * 3 does not match TimeUnit.SECONDS * 180, but that also makes synchronization less accurate.
Exact accuracy on a scale of minutes is quite acceptable in my case. I was just wondering if anyone knows if this is really intentional behavior or something I have to worry about ...
Despite the fact that my question has been answered, I include a small code example here if someone might be interested in testing it:
public static void main(String[] args) { ScheduledExecutorService exec = Executors .newSingleThreadScheduledExecutor(); exec.scheduleWithFixedDelay(new UpdateTask(), 0, 3, TimeUnit.MINUTES); Scanner sc = new Scanner(System.in); boolean quitted = false; while (!quitted) { String command = sc.nextLine(); if (command.equals("q")) quitted = true; } exec.shutdown(); } private static final class UpdateTask implements Runnable { @Override public void run() { System.out.println("bg process running (" + (new Date()) + ")"); } }
This code snippet resulted (when it is left in the background on my system, when you do all kinds of other things):
bg process running (Thu Oct 18 10:49:48 EEST 2012) bg process running (Thu Oct 18 10:52:54 EEST 2012) bg process running (Thu Oct 18 10:55:57 EEST 2012) bg process running (Thu Oct 18 10:58:59 EEST 2012) bg process running (Thu Oct 18 11:02:02 EEST 2012) bg process running (Thu Oct 18 11:05:05 EEST 2012) bg process running (Thu Oct 18 11:08:07 EEST 2012)
The problem should not be what Quoi suggested (thanks for that), since I am running Win7, so this is probably due to Win7 thread scheduling, priorities and significant load on my machine.
source share