美文网首页
Timer schedule()与scheduleAtFixed

Timer schedule()与scheduleAtFixed

作者: rrsunhome | 来源:发表于2019-10-22 18:02 被阅读0次

不延迟

  • schedule() 下一个任务在上一个任务开始计时执行
  • scheduleAtFixedRate() 下一个任务在上一个任务结束后执行

延迟

下一个任务在上一个任务结束后开执行

代码示例

···java
public class TimerApiBootstrap {

public static void main(String[] args) {
    // testSchedule();

   // testDelaySchedule();

    testDelayScheduleAtFixedRate();

}

private static void testDelayScheduleAtFixedRate() {
    Timer timer = new Timer();

    DelayTimerTask delayTimerTask = new DelayTimerTask();
    try {
        timer.scheduleAtFixedRate(delayTimerTask, DateUtils.parse("2019-10-22 15:28:00"), 2000);
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

private static void testDelaySchedule() {
    Timer timer = new Timer();

    DelayTimerTask delayTimerTask = new DelayTimerTask();

    try {
        timer.schedule(delayTimerTask, DateUtils.parse("2019-10-22 15:28:00"), 2000);
    } catch (ParseException e) {
        e.printStackTrace();
    }


}

private static void testSchedule() {
    // 设置daemon为守护线程
    Timer timer = new Timer(true);
    SystemTimerTask systemTimerTask = new SystemTimerTask();
    try {
        // timer.schedule(systemTimerTask, DateUtils.parse("2019-10-22 15:16:00"));

        timer.schedule(systemTimerTask, DateUtils.parse("2019-10-22 15:19:00"), 2000);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

}

class DelayTimerTask extends TimerTask {

@Override
public void run() {
    System.out.println("begin" + Thread.currentThread().getName() + ":" + DateUtils.format(new Date()));

    // 睡眠三秒,模拟延迟
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("end" + Thread.currentThread().getName() + ":" + DateUtils.format(new Date()));
}

}

class SystemTimerTask extends TimerTask {

@Override
public void run() {
    System.out.println("time:" + DateUtils.format(new Date()));
}

}

class DateUtils {

private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");


public static String format(Date date) {
    return sdf.format(date);
}

public static Date parse(String dateStr) throws ParseException {
    return sdf.parse(dateStr);
}

}

···

源码解析

源码图片
  • schedule在计算下一次执行的时间的时候,是通过当前时间 + 时间片
  • scheduleAtFixedRate方法是通过预计时间+ 时间片

github 地址

https://github.com/rrsunhome/sunhome-framework

相关文章

网友评论

      本文标题:Timer schedule()与scheduleAtFixed

      本文链接:https://www.haomeiwen.com/subject/fdqcvctx.html