jdk 自带的 timer 框架是有缺陷的, 其功能简单,而且有时候它的api 不好理解。
import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TestTimer { private static final int delay = 1000; /** * @param args */ public static void main(String[] args) { Timer t = new Timer(); int seconds = 2; TimerTask task = new SimpleTask(); t.schedule(task , delay, seconds * 1000); } } class SimpleTask extends TimerTask{ @Override public void run() { System.out.println("SimpleTask.run() 11 " + new Date()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } //System.out.println("SimpleTask.run() 22 " + new Date()); } }
结果为
SimpleTask.run() 11 Mon May 30 16:43:58 CST 2016
SimpleTask.run() 11 Mon May 30 16:44:02 CST 2016
SimpleTask.run() 11 Mon May 30 16:44:06 CST 2016
显示是每隔4秒, 而不是我想象的 period + sleep time 即 2+4 = 6s, why ??
原来是这样的:
参考: http://stackoverflow.com/questions/15128937/java-util-timer-fixed-delay-not-working
Nope, that‘s how it is intended to work. The period is the period between start times, not the period between an end time and the next start time.
Basically you‘re telling it in plain english "start at 1 second and execute every two seconds after that" so 1, 3, 5, 7, etc is the logical interpretation.
shareimprove this answer
answered Feb 28 ‘13 at 6:34
Affe
31k25064
Ok, I re-read the Javadoc again. That means ‘schedule‘ uses previous task‘s start-time as reference (2nd task will reference 1st task, 3rd task will reference 2nd task). While ‘scheduleAtFixedRate‘ always use the first task‘s start-time as reference (all task‘s start-time are based on the 1st task‘s start-time). Is that how it works? – Dave Xenos Feb 28 ‘13 at 6:52
Yeah, the way I think of it is if ‘schedule‘ misses one, it forgets about it, if ‘scheduleAtFixedRate‘ misses one, it puts in a make-up. – Affe Mar 1 ‘13 at 2:17