定时任务 ScheduledExecutorService

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

/**
 * ScheduledExecutorService是从Java SE 5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
 * 相比于上两个方法(普通thread和用Timer、TimerTask),它有以下好处:
 * 相比于Timer的单线程,它是通过线程池的方式来并发执行任务的
 * 可以很灵活的去设定第一次执行任务delay时间
 * 提供了良好的约定,以便设定执行的时间间隔
 */
public class Timer implements Runnable  {

    private String something;
    private int index = 0;

    public Timer(String something) {
        this.something = something;
    }

    @Override
    public void run() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if("beautiful".equals(something)) {
            if (index == "beautiful".length()) {
                System.out.println();
                System.out.println(df.format(new Date()) + "  " + "beautiful!!!");
                index = 0;
            } else {
                if (index == 0)
                    System.out.print(df.format(new Date()) + "  ");
                System.out.print("beautiful".charAt(index));
                index++;
            }
        }else{
            System.out.println(df.format(new Date())+"  "+something);
        }
    }

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
        System.out.println(df.format(new Date())+"  you are");

        long initialDelay1 = 1;
        //从现在开始1秒钟之后,只执行一次
        service.schedule(new Timer("... ..."), initialDelay1,TimeUnit.SECONDS);

        long initialDelay2 = 2; //延迟
        long period2 = 1; //间隔
        // 从现在开始2秒钟之后,每隔1秒钟执行一次
        // scheduleAtFixedRate 每隔固定的时间,立即执行下一次。(scheduleWithFixedDelay 等上一次任务执行完毕,才会执行下一次)
        service.scheduleAtFixedRate(new Timer("beautiful"),initialDelay2, period2, TimeUnit.SECONDS);
    }
}

结果:

2018-09-19 14:01:52  you are
2018-09-19 14:01:53  ... ...
2018-09-19 14:01:54  beautiful
2018-09-19 14:02:03  beautiful!!!
2018-09-19 14:02:04  beautiful
2018-09-19 14:02:13  beautiful!!!
。。。

 

posted on 2018-09-19 14:04  书生游  阅读(555)  评论(0编辑  收藏  举报