本文实例主要进行java Timer(定时调用、固定时间执行)测试,具体实现代码如下。
测试1
当任务执行时间小于重复执行的间隔时间
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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
当任务执行时间大于重复执行的间隔时间
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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测试定时调用及固定时间执行代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://blog.csdn.net/hl_java/article/details/79035344