Regular tasks -ScheduledExecutorService

Create a scheduled task thread pool

ScheduledExecutorService executorService = Executors.newScheduledThreadPool (4); // not recommended 

// or
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(4);// 推荐

 

Create a scheduled task

public interface ScheduledExecutorService extends ExecutorService {

  public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);

  public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);

  public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
  public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); }

 

This example creates a scheduled task

Example 1: delay execution

package com.java.scheduled.task.pool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskDemo01 {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(4);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DATE DATE = new new DATE (); 
        System.out.println ( "scheduling of tasks:" + sdf.format (DATE));
         Long C1 = date.getTime (); 
        the Runnable Runnable = () -> { 
            DATE nowDate = new new a Date (); 
            System.out.println ( "**** Scheduled tasks (1): [2 second delay execution]" ); 
            System.out.println ( "real time mission:" + sdf.format (nowDate)); 
            System.out.println ( "delay time:" + (nowDate.getTime () - C1) + "MS" ); 
        }; 
        executorService.schedule (Runnable,2 , TimeUnit.SECONDS);
    }
    
}

Execution results are as follows:

The timing of implementation of tasks: 2019-05-28 12:10:46 
**** Scheduled Tasks (1 ): [2 second delay enforcement of a 
real mission time: 2019-05-28 12:10:48 
delay time : 2087ms

 

Example Two: deferred execution, returning a result

package com.java.scheduled.task.pool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

public class ScheduledTaskDemo02 {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        System.out.println("安排执行任务的时间:"+sdf.format (DATE));
         Long C2 = date.getTime (); 
        a Callable <String> Callable = () -> { 
            a Date nowDate = new new a Date (); 
            System.out.println ( "**** Program Tasks ( 2): [2 second delay are performed to return the end result] " ); 
            System.out.println ( " time actually perform the task: "+ sdf.format (nowDate)); 
            System.out.println ( " delay time: "+ (nowDate.getTime () - c2) +" MS " ); 
            Thread.sleep ( 1000 ); 
            System.out.println ( " task is finished, the current time: "+ sdf.format ( new new a Date ())) ;
             return "success";
        };
        ScheduledFuture<String> scheduledFuture = executorService.schedule(callable, 2, TimeUnit.SECONDS);
        try {
            System.out.println("任务的执行结果:"+scheduledFuture.get());
        } catch (ExecutionException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        }
    }

}

Execution results are as follows:

The timing of implementation of tasks: 2019-05-28 12:14:05 
**** scheduled task (2 ): [2 second delay execution, execution returns to the end result] 
the actual time to perform tasks: 2019-05-2812: 14:07 
delay time: 2072ms 
task is finished, the current time: 2019-05-28 12:14:08 
execution results of the task: success

 

Example Three: delay task performed periodically +

package com.java.scheduled.task.pool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskDemo03 {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new new a Date (); 
        System.out.println ( "scheduling of tasks:" + sdf.format (DATE));
         Long C3 = date.getTime (); 
        the Runnable Runnable = new new the Runnable () {
             Long exeTime = C3; 
            @override 
            public  void RUN () { 
                a Date nowDate = new new a Date (); 
                System.out.println ( "--------------------------- -------------------------------------------------- --- " ); 
                System.out.println ( " Scheduled tasks (3): [1 second delay the implementation of the first task, after performing the task every two seconds] " );
                System.out.println ( "**** actual mission time:" + sdf.format (nowDate)); 
                System.out.println ( "**** mission since the last time interval:" + ( nowDate.getTime () - exeTime) + "MS" );
                 the try { 
                    the Thread.sleep ( 4000 ); 
                } the catch (InterruptedException E) {} 
                exeTime = nowDate.getTime (); 
            } 
        }; 
        executorService.scheduleAtFixedRate (Runnable, . 1, 2 , TimeUnit.SECONDS); 
    } 

}

Execution results are as follows:

The timing of implementation of tasks: 2019-05-28 12:15:12 
---------------------------------- ---------------------------------------------- 
scheduled task ( 3 ): [1 second delay the implementation of the first task, after every two seconds to perform a task]
 actually perform the task **** time: 2019-05-28 12:15:13 
**** from the last mission interval: 1003ms
 --------------------------------------------- ----------------------------------- 
scheduled task ( 3 ): [1 second delay the implementation of the first mission , after which a task every two seconds]
 **** actually perform the task time: 2019-05-28 12:15:17 
**** from the last time interval to perform tasks: 4002ms
 ------ -------------------------------------------------- ------------------------ 
Scheduled tasks ( 3 ): [1 second delay the implementation of the first task, after every two seconds to perform a task]
 * *** the actual time to perform tasks: 2019-05-28 12:15:21 
**** from the last time interval to perform tasks: 4001ms
-------------------------------------------------- ------------------------------ 
scheduled task ( 3 ): [1 second delay the implementation of the first task, after every 2 seconds to perform a task]
 actually perform the task **** time: 2019-05-28 12:15:25 
**** time interval from the last mission: 4002ms

 

Example 4: The initial delay + delay periodic tasks

package com.java.scheduled.task.pool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskDemo04 {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new new a Date (); 
        System.out.println ( "scheduling of tasks:" + sdf.format (DATE));
         Long C3 = date.getTime (); 
        the Runnable Runnable = new new the Runnable () {
             Long exeTime = C3; 
            @override 
            public  void RUN () { 
                a Date nowDate = new new a Date (); 
                System.out.println ( "--------------------------- -------------------------------------------------- --- " ); 
                System.out.println ( " Scheduled tasks (4): [1 second delay the implementation of the first task, after performing the task every two seconds] " );
                System.out.println ( "**** actual mission time:" + sdf.format (nowDate)); 
                System.out.println ( "**** mission since the last time interval:" + ( nowDate.getTime () - exeTime) + "MS" );
                 the try { 
                    the Thread.sleep ( 2500 ); 
                } the catch (InterruptedException E) {} 
                exeTime = nowDate.getTime (); 
            } 
        }; 
        executorService.scheduleWithFixedDelay (Runnable, . 1, 2 , TimeUnit.SECONDS); 
    } 

}

Execution results are as follows:

The timing of implementation of tasks: 2019-05-28 12:16:56 
---------------------------------- ---------------------------------------------- 
scheduled task ( 4 ): [1 second delay the implementation of the first task, after every two seconds to perform a task]
 actually perform the task **** time: 2019-05-28 12:16:57 
**** from the last mission interval: 1018ms
 --------------------------------------------- ----------------------------------- 
scheduled task ( 4 ): [1 second delay the implementation of the first mission , after which a task every two seconds]
 **** actually perform the task time: 2019-05-28 12:17:01 
**** from the last time interval to perform tasks: 4504ms
 ------ -------------------------------------------------- ------------------------ 
Scheduled tasks ( 4 ): [1 second delay the implementation of the first task, after every two seconds to perform a task]
 * *** the actual time to perform tasks: 2019-05-28 12:17:06 
**** from the last time interval to perform tasks: 4502ms
-------------------------------------------------- ------------------------------ 
scheduled task ( 4 ): [1 second delay the implementation of the first task, after every 2 seconds to perform a task]
 actually perform the task **** time: 2019-05-28 12:17:10 
**** time interval from the last mission: 4502ms

 

Guess you like

Origin www.cnblogs.com/517cn/p/10936460.html