- schedule() 下一个任务在上一个任务开始计时执行
- scheduleAtFixedRate() 下一个任务在上一个任务结束后执行
-
源码解析:import java.text.SimpleDateFormat; import java.util.Timer; import java.util.TimerTask; public class TimerTest { public static void main(String[] args) { final Timer timer = new Timer(); // timer.schedule(new TimerTask() { timer.scheduleAtFixedRate(new TimerTask() { int count = 1; @Override public void run() { count++; if (count == 10) { try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("延迟5s"); e.printStackTrace(); } } SimpleDateFormat sf = new SimpleDateFormat( "yyyy MM dd hh:mm:ss"); System.out.println("当前时间:" + sf.format(System.currentTimeMillis()) + "计划时间:" + sf.format(scheduledExecutionTime())); } },1000,1000); } }
- schedule在计算下一次执行的时间的时候,是通过当前时间 + 时间片
- scheduleAtFixedRate方法是通过预计时间+ 时间片
Timer.schedule()与timer.scheduleAtFixedRate()的区别
最新推荐文章于 2022-05-11 19:44:21 发布