schedule方法和scheduleAtFixedRate方法的区别

schedulescheduleAtFixedRate方法都可以实现任务的延时和不延时执行且都会按顺序执行,因此不需要考虑非线程安全的情况。它们的主要区别只在于有没有追赶特性。其中,schedule方法不具有追赶特性,而scheduleAtFixedRate方法具有追赶特性。

首先验证schedule方法不具有追赶执行性

public class App {
    public static void main( String[] args ) {
        MyTask myTask = new MyTask();
        System.out.println("当前执行时间为: " + new Date());
        Calendar c = Calendar.getInstance();
        c.set(Calendar.SECOND, c.get(Calendar.SECOND) - 5);
        Date runDate = c.getTime();
        System.out.println("计划执行时间为: " + runDate);
        Timer timer = new Timer();
        //调用的是schedule方法,验证其不具追赶性
        timer.schedule(myTask, runDate, 1000);
    }
}

class MyTask extends TimerTask {
    @Override
    public void run() {
        System.out.println("time = " + new Date());
    }
}

运行结果

当前执行时间为: Sat Apr 06 17:56:50 CST 2017
计划执行时间为: Sat Apr 06 17:56:45 CST 2017
time = Sat Apr 06 17:56:50 CST 2017
time = Sat Apr 06 17:56:51 CST 2017
time = Sat Apr 06 17:56:52 CST 2017
time = Sat Apr 06 17:56:53 CST 2017
time = Sat Apr 06 17:56:54 CST 2017
time = Sat Apr 06 17:56:55 CST 2017
time = Sat Apr 06 17:56:56 CST 2017
time = Sat Apr 06 17:56:57 CST 2017

时间Sat Apr 06 17:56:45 CST 2017Sat Apr 06 17:56:50 CST 2017之间的时间所对应的Task任务就被取消掉,不被执行了,这就是Task任务不追赶。

验证scheduleAtFixedRate方法具有追赶执行性

public class App {
    public static void main( String[] args ) {
        MyTask myTask = new MyTask();
        System.out.println("当前执行时间为: " + new Date());
        Calendar c = Calendar.getInstance();
        c.set(Calendar.SECOND, c.get(Calendar.SECOND) - 5);
        Date runDate = c.getTime();
        System.out.println("计划执行时间为: " + runDate);
        Timer timer = new Timer();
        //调用scheduleAtFixedRate方法,测试其具有追赶性
        timer.scheduleAtFixedRate(myTask, runDate, 1000);
    }
}

class MyTask extends TimerTask {
    @Override
    public void run() {
        System.out.println("time = " + new Date());
    }
}

运行结果

当前执行时间为: Sat Apr 06 17:58:30 CST 2017
计划执行时间为: Sat Apr 06 17:58:25 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:31 CST 2017
time = Sat Apr 06 17:58:32 CST 2017
time = Sat Apr 06 17:58:33 CST 2017
time = Sat Apr 06 17:58:34 CST 2017
time = Sat Apr 06 17:58:35 CST 2017
time = Sat Apr 06 17:58:36 CST 2017
time = Sat Apr 06 17:58:37 CST 2017

将两个时间段内所对应的Task任务被“补充性”地执行,这就是Task任务追赶特性。

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/26/difference-between-schedule-method-and-scheduleatfixedrate-method/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
schedule方法和scheduleAtFixedRate方法的区别
schedule和scheduleAtFixedRate方法都可以实现任务的延时和不延时执行且都会按顺序执行,因此不需要考虑非线程安全的情况。它们的主要区别只在于有没有追赶特……
<<上一篇
下一篇>>
文章目录
关闭
目 录