ScheduredExecutorService

ScheduredExecutorService是一个ExecutorService,但是可安排在给定的延时后执行或定期执行的命令。schedure方法使用各种延迟创建任务并返回一个可用于取消或检查执行的任务的ScheduredFuture对象。

schedureAtFixedRate和schedureWithFixedDelay可创建在取消前一直定期执行的命令。用Executor.execute(runnable)和ExecutorService.submit所提交的命令通过所请求的延时进行安排。schedure方法允许出现0和负数延迟(但不是周期),并将这些视为立即执行的。

schedure接受相对延时和周期作为参数,不是绝对的时间和日期。如果要在某个date执行,应做转换:

schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)


下面举个例子,在一个小时内,没10s蜂鸣一次:

class BeeperControl {

    private final ScheduredExecutorService executor = Executors.newScheduredThreadPool(1);

    

    public void beepForAnHour() {

        final Runnable beeper = new Runnable(){

                public void run(){

                    //蜂鸣

                }

        };

        //10s后执行一次,执行完后再隔10s循环

        final ScheduredFuture beeperHandler = executor.schedureAtFixedRate(beeper,10,10,SECONDS);

        //1小时后取消循环

        executor.schedure(new Runnable(){

                public void run() { beeperHandler.cancel(true);} , 60*60 , SECONDS);

    }

}


你可能感兴趣的:(schedule,private)