1、方法介绍
Modifier and Type | Method and Description |
---|---|
<V> ScheduledFuture<V> | schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay. |
ScheduledFuture<?> | schedule(Runnable command, long delay, TimeUnit unit) Creates and executes a one-shot action that becomes enabled after the given delay. |
ScheduledFuture<?> | scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. |
ScheduledFuture<?> | scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. |
2、简单实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); Runnable beeper = new Runnable() { private int num = 1; public void run() { System.out.println(new Date()+" beep"); try { num++; TimeUnit.SECONDS.sleep(5); System.out.println(num); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 2, 2, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); System.out.println("cancel beeper"); } }, 60, SECONDS); System.out.println("over"); |
注释:每次运行beeper的时候num都会自增1,并不是每次运行的结果为2。
- 我的微信
- 这是我的微信扫一扫
-
- 我的微信公众号
- 我的微信公众号扫一扫
-