ScheduledExecutorService Executors achieve timing task framework

I. Introduction

Schedule Commands that ExecutorService CAN AN to RUN A GIVEN the After Delay, or to the Execute PERIODICALLY.
(ExecutorService can schedule commands to run after a given delay or periodically.)

Schedule Tasks with the Create Methods at The Various delays and return that CAN BE A Task Object Used to the Cancel or the Check Execution. ScheduleAtFixedRate and scheduleWithFixedDelay at The Methods and the Execute the Create Tasks that an until RUN PERIODICALLY Canceled.
(Scheduling method will create tasks with various delays, and can be used to return a task object or canceled checks performed. scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks run periodically until it is canceled.
)

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.
(use Executor.execute (java.lang.Runnable) and ExecutorService commit command method to submit plans for zero delay scheduling method also allows for zero delay and negative delay (but not allowed to use the cycle), and treated as request immediately executed.
)

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.
(All scheduling methods accept relative delays and periods as arguments, rather than absolute time or date as a parameter. The absolute time represents the date of conversion to the required form is very simple. For example, to program planning at some future date, You can use:. schedule (task, date.getTime ( ) - System.currentTimeMillis (), TimeUnit.MILLISECONDS) but please note that due to network time synchronization protocols, clock drift or other factors, the relative delay expiration time does not have to enable the task consistent with the current date. the Executors class package provided for this ScheduledExecutorService implementation provides a convenient factory methods.
)

(jdk7 doc , translate by google )

Second, the timing of two common tasks

1.

Creates and performs a periodic operation, the first operation will be enabled after a given initial delay, and enable a given period of time; i.e., after the execution will then start the initialDelay initialDelay + cycle, and then initialDelay + 2 * cycle, and so on.

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

2. ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

Create and execute a periodical operation, the first operation will be enabled after a given initial delay, then execution terminates with a given delay between the start of the next execution.

3. ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)

Create and execute a operation that becomes enabled after the given delay.

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
System.out.println("一次性的延迟任务, 10S 后执行");
executorService.schedule(new Runnable() {
    @Override
    public void run() {
        System.out.println("一次性延迟任务");
    }
}, 10L, SECONDS);
        

4. ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit)

Create and execute ScheduledFuture, the ScheduledFuture after a given delay becomes enabled.

Third, the sample code

class PrintControl {
    private final SimpleDateFormat SDF = new SimpleDateFormat("hh:mm:ss");

    /**
     * @param int corePoolSize 线程池中最小的线程数, 无任务时保持, 任务过多时可以超出这个值
     */


    private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
//    private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1, Executors.defaultThreadFactory());

    /**
     * 给定延迟的打印任务
     * 以固定的延迟时间(delay)去执行任务
     */
    public void printForDelay() {
        Runnable print = () -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("ScheduledWithFixedDelay" + SDF.format(new Date()));
        };

        /**
         * @param Runnable command
         * @param long initialDelay
         * @param long delay
         * @param TimeUnit unit
         */
        scheduled.scheduleWithFixedDelay(print, 0L, 5L, SECONDS);
    }

    /**
     * 定期去执行打印任务
     * 以固定的周期(period)去执行任务
     */
    public void printForRate() {
        Runnable print = () -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("ScheduledAtFixedRate" + SDF.format(new Date()));
        };

        /**
         * @param Runnable command
         * @param long initialDelay
         * @param long period
         * @param TimeUnit unit
         */
        scheduled.scheduleAtFixedRate(print, 0L, 5L, SECONDS);
    }


}

class PrintThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, "PrintThreadFactory");
    }
}

Fourth, the task thread name specified by ThreadFactory

V. Conditional End Task

Sixth, reference

Guess you like

Origin www.cnblogs.com/52liming/p/11610317.html