注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

和申的个人主页

专注于java开发,1985wanggang

 
 
 

日志

 
 

ScheduledExecutorService定时  

2012-06-05 14:56:46|  分类: Java |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

ScheduledExecutorService接口
在ExecutorService的基础上,ScheduledExecutorService提供了按时间安排执行任务的功能,它提供的方法主要有:
schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。
代码:ScheduleExecutorService的例子

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceTest
{
public static void main(String[] args) throws InterruptedException,ExecutionException
{
//*1
ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
//*2
Runnable task1=new Runnable()
{
public void run()
{
System.out.println("Taskrepeating.");
}
};
//*3
final ScheduledFuture future1=service.scheduleAtFixedRate(task1,0,1,TimeUnit.SECONDS);
//*4
ScheduledFuture future2=service.schedule(new Callable()
{
public String call()
{
future1.cancel(true);
return "taskcancelled!";
}
},10,TimeUnit.SECONDS);
System.out.println(future2.get());
//*5
service.shutdown();
}
}


这个例子有两个任务,第一个任务每隔一秒打印一句“Taskrepeating”,第二个任务在5秒钟后取消第一个任务。


*1:初始化一个ScheduledExecutorService对象,这个对象的线程池大小为2。
*2:用内函数的方式定义了一个Runnable任务。
*3:调用所定义的ScheduledExecutorService对象来执行任务,任务每秒执行一次。能重复执行的任务一定是Runnable类型。注意我们可以用TimeUnit来制定时间单位,这也是Java5.0里新的特征,5.0以前的记时单位是微秒,现在可精确到奈秒。
*4:调用ScheduledExecutorService对象来执行第二个任务,第二个任务所作的就是在5秒钟后取消第一个任务。

*5:关闭服务。





java.util.concurrent
Interface ScheduledExecutorService

All Superinterfaces:
Executor, ExecutorService
All Known Implementing Classes:
ScheduledThreadPoolExecutor

public interface ScheduledExecutorService
extends ExecutorService
  

An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.

Commands submitted using the Executor.execute(java.lang.Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.

All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors. The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

Usage Example

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
 import static java.util.concurrent.TimeUnit.*;
   class BeeperControl {
      private final ScheduledExecutorService scheduler =         Executors.newScheduledThreadPool(1);
        public void beepForAnHour() {
          final Runnable beeper = new Runnable() {
                  public void run() {
 System.out.println("beep"); } 
             };
          final ScheduledFuture<?> beeperHandle =              scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
          scheduler.schedule(new Runnable() { 
                 public void run() { beeperHandle.cancel(true); } 
             }, 60 * 60, SECONDS);      }
   }   

Since:
1.5

Method Summary
<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.
Methods inherited from interface java.util.concurrent.ExecutorService
awaitTermination, invokeAll, invokeAll, invokeAny, invokeAny, isShutdown, isTerminated, shutdown, shutdownNow, submit, submit, submit
Methods inherited from interface java.util.concurrent.Executor
execute

Method Detail

schedule

ScheduledFuture<?> schedule(Runnable command,                              long delay,                              TimeUnit unit)
Creates and executes a one-shot action that becomes enabled after the given delay.

Parameters:
command - the task to execute
delay - the time from now to delay execution
unit - the time unit of the delay parameter
Returns:
a ScheduledFuture representing pending completion of the task and whose get() method will return null upon completion
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if command is null

schedule

<V> ScheduledFuture<V> schedule(Callable<V> callable,                                  long delay,                                  TimeUnit unit)
Creates and executes a ScheduledFuture that becomes enabled after the given delay.

Parameters:
callable - the function to execute
delay - the time from now to delay execution
unit - the time unit of the delay parameter
Returns:
a ScheduledFuture that can be used to extract result or cancel
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if callable is null

scheduleAtFixedRate

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. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

Parameters:
command - the task to execute
initialDelay - the time to delay first execution
period - the period between successive executions
unit - the time unit of the initialDelay and period parameters
Returns:
a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if command is null
IllegalArgumentException - if period less than or equal to zero

scheduleWithFixedDelay

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. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.

Parameters:
command - the task to execute
initialDelay - the time to delay first execution
delay - the delay between the termination of one execution and the commencement of the next
unit - the time unit of the initialDelay and delay parameters
Returns:
a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
Throws:
RejectedExecutionException - if the task cannot be scheduled for execution
NullPointerException - if command is null
IllegalArgumentException - if delay less than or equal to zero
  评论这张
 
阅读(1801)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016