java Timer测试定时调用及固定时间执行代码示例

本文实例主要进行java Timer(定时调用、固定时间执行)测试,具体实现代码如下。

测试1

当任务执行时间小于重复执行的间隔时间

代码:

public class TimerTest2 {

public static void main(String[] args) throws InterruptedException {

Timer timer = new Timer();

timer.schedule(new MyTask(0), 1000, 10000);

//timer.schedule(new MyTask(1), 1000, 10000);

}

static class MyTask extends TimerTask {

private final int i;

public MyTask(int i) {

this.i = i;

}

@Override

public void run() {

System.out.println(i + "dddd" + DateTimeUtil.getDateTimeString("yyyy-MM-dd HH:mm:ss.SSS"));

try {

if (i == 0) {

Thread.sleep(8000L);

} else {

Thread.sleep(13000L);

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

结果:

0dddd2018-01-11 15:34:57.826

0dddd2018-01-11 15:35:07.824

0dddd2018-01-11 15:35:17.824

0dddd2018-01-11 15:35:27.824

0dddd2018-01-11 15:35:37.824

0dddd2018-01-11 15:35:47.824

0dddd2018-01-11 15:35:57.824

0dddd2018-01-11 15:36:07.824

0dddd2018-01-11 15:36:17.824

0dddd2018-01-11 15:36:27.824

0dddd2018-01-11 15:36:37.824

0dddd2018-01-11 15:36:47.824

0dddd2018-01-11 15:36:57.824

0dddd2018-01-11 15:37:07.824

0dddd2018-01-11 15:37:17.824

0dddd2018-01-11 15:37:27.824

0dddd2018-01-11 15:37:37.824

测试2

当任务执行时间大于重复执行的间隔时间

代码:

public class TimerTest2 {

public static void main(String[] args) throws InterruptedException {

Timer timer = new Timer();

//timer.schedule(new MyTask(0), 1000, 10000);

timer.schedule(new MyTask(1), 1000, 10000);

}

static class MyTask extends TimerTask {

private final int i;

public MyTask(int i) {

this.i = i;

}

@Override

public void run() {

System.out.println(i + "dddd" + DateTimeUtil.getDateTimeString("yyyy-MM-dd HH:mm:ss.SSS"));

try {

if (i == 0) {

Thread.sleep(8000L);

} else {

Thread.sleep(13000L);

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

结果:

1dddd2018-01-11 16:03:07.575

1dddd2018-01-11 16:03:20.601

1dddd2018-01-11 16:03:33.602

1dddd2018-01-11 16:03:46.603

1dddd2018-01-11 16:03:59.604

1dddd2018-01-11 16:04:12.606

1dddd2018-01-11 16:04:25.607

1dddd2018-01-11 16:04:38.608

总结

以上是 java Timer测试定时调用及固定时间执行代码示例 的全部内容, 来源链接: utcz.com/z/313397.html

回到顶部