The examples in this article mainly conduct java Timer (timed call, fixed time execution) tests, and the specific implementation code is as follows.
When the task execution time is less than the interval time of repeated execution
Code:
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(); } } }}result:
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
When the task execution time is greater than the interval time of repeated execution
Code:
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(); } } }}result:
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
The above is all the content of this article about java Timer test timing calls and fixed-time code execution examples. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!