不延迟
- 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方法是通过预计时间+ 时间片
网友评论