ScheduleExecutorService定时调用

一:简单说明java

ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便。并发

下面是该接口的原型定义ide

Java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executorthis

接口scheduleAtFixedRate原型定义及参数说明spa

ScheduledFuture<?> java.util.concurrent.ScheduledExecutorService.scheduleAtFixedRate(.net

        Runnable command,线程

        long initialDelay,orm

        long period,server

        TimeUnit unit)接口

command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位

接口scheduleWithFixedDelay原型定义及参数说明

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  

                long initialDelay,  

                long delay,  

                TimeUnit unit);  

command:执行线程
initialDelay:初始化延时
period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
unit:计时单位

二:功能示例

1.按指定频率周期执行某个任务。

初始化延迟0ms开始执行,每隔100ms从新执行一次任务。

/** 

 * 以固定周期频率执行任务 

 */  

public static void executeFixedRate() {  

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  

    executor.scheduleAtFixedRate(  

            new EchoServer(),  

            0,  

            100,  

            TimeUnit.MILLISECONDS);  

}  

间隔指的是连续两次任务开始执行的间隔。

 

2.按指定频率间隔执行某个任务。

初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。

/** 

 * 以固定延迟时间进行执行 

 * 本次任务执行完成后,须要延迟设定的延迟时间,才会执行新的任务 

 */  

public static void executeFixedDelay() {  

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  

    executor.scheduleWithFixedDelay(  

            new EchoServer(),  

            0,  

            100,  

            TimeUnit.MILLISECONDS);  

}  

3.周期定时执行某个任务。

有时候咱们但愿一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,能够使用下面方法设定天天在固定时间执行一次任务。

/** 

 * 天天晚上8点执行一次 

 * 天天定时安排任务进行执行 

 */  

public static void executeEightAtNightPerDay() {  

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  

    long oneDay = 24 * 60 * 60 * 1000;  

    long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  

    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  

  

    executor.scheduleAtFixedRate(  

            new EchoServer(),  

            initDelay,  

            oneDay,  

            TimeUnit.MILLISECONDS);  

/** 

 * 获取指定时间对应的毫秒数 

 * @param time "HH:mm:ss" 

 * @return 

 */  

private static long getTimeMillis(String time) {  

    try {  

        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  

        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  

        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  

        return curDate.getTime();  

    } catch (ParseException e) {  

        e.printStackTrace();  

    }  

    return 0;  

}  

4.辅助代码

class EchoServer implements Runnable {  

    @Override  

    public void run() {  

        try {  

            Thread.sleep(50);  

        } catch (InterruptedException e) {  

            e.printStackTrace();  

        }  

        System.out.println("This is a echo server. The current time is " +  

                System.currentTimeMillis() + ".");  

    }  

}  

三:一些问题

上面写的内容有不严谨的地方,好比对于scheduleAtFixedRate方法,当咱们要执行的任务大于咱们指定的执行间隔时会怎么样呢?

对于中文API中的注释,咱们可能会被忽悠,认为不管怎么样,它都会按照咱们指定的间隔进行执行,其实当执行任务的时间大于咱们指定的间隔时间时,它并不会在指定间隔时开辟一个新的线程并发执行这个任务。而是等待该线程执行完毕。

源码注释以下:

* 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  

* <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then  

* <tt>initialDelay + 2 * period</tt>, 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.  

根据注释中的内容,咱们须要注意的时,咱们须要捕获最上层的异常,防止出现异常停止执行,致使周期性的任务再也不执行。

相关文章
相关标签/搜索