开发者

Java System Clock Independent Scheduling/Pausing

开发者 https://www.devze.com 2023-01-31 05:07 出处:网络
I need a way to pause/sleep a thread in a system clock independent way. Me开发者_开发问答aning, that if I want a Thread to weak up in dT msecs it must do so also if the system time changes significant

I need a way to pause/sleep a thread in a system clock independent way. Me开发者_开发问答aning, that if I want a Thread to weak up in dT msecs it must do so also if the system time changes significantly during this time. I am not so much interested in accuracy in msecs and more in principle that it will work.

TimerTasks are not an option since they work on absolute time.


Thread.sleep(millis);


Tricky.... it's tough to know if the system clock is even being used for any given strategy. However, your avoidance of the clock is because the time might be changed during the thread pause, but System.nanoTime() is independent of the current time since it is purely the number of nanoseconds since the JVM started. Accordingly, if the pause strategy uses nanos, one might assume that the pause periods will retain accuracy through system clock time changes. Perhaps Thread.join(0, nanos) called in a loop:

public static void pause(long ms) throws InterruptedException {
   long final ZERO = 0L;
   int final MAX_NANOS = 999999;
   for(int i = 0; i < ms+1; i++) {
      Thread.currentThread().join(ZERO, MAX_NANOS);
   }
}

I did not test with system clock changes, but it appears to run within a .004% deviation.


I'm not sure if I understand your question correctly. If you need a task scheduler, Quartz is pretty good. If you actually want to pause an arbitrary thread for x amount of time than that can be a little more tricky.

0

精彩评论

暂无评论...
验证码 换一张
取 消