任务调度ScheduledExecutorService,实现定时任务执行

1.ScheduledExecutorService的主要作用就是可以将定时任务与线程池功能结合使用。

2.scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便,两者的区别:

scheduleAtFixedRate :是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕,如果上一个任务执行完毕,则当前任务立即执行,如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行。

scheduleWithFixedDelay:是以上一个任务结束时开始计时,period时间过去后,立即执行。

3.scheduleWithFixedDelay API接口

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

 

示例:

public void test() {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                System.err.println("+++++++++++++++++++++++++++++++");
            }
        });
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    //每隔2s执行一次任务,
TimeUnit.MILLISECONDS可以调节任务执行周期
executor.scheduleWithFixedDelay(thread, 0, 2000, TimeUnit.MILLISECONDS); }

4.scheduleAtFixedRate API接口

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

示例:

/**
     * 每天晚上8点执行一次 每天定时安排任务进行执行
     */
    public static void executeEightAtNightPerDay() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        long oneDay = 24 * 60 * 60 * 1000;
        long initDelay = getTimeMillis("10:23:00") - System.currentTimeMillis();
        initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;

        executor.scheduleAtFixedRate(new Thread(new Runnable() {

            @Override
            public void run() {
                System.err.println("----------------------------------");
            }
        }), initDelay, oneDay, TimeUnit.HOURS);
    }

    /**
     * 获取指定时间对应的毫秒数
     * 
     * @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;
        }
    }

 

posted @ 2018-10-24 14:28  Azjs丶V1  阅读(1347)  评论(0)    收藏  举报