码迷,mamicode.com
首页 > 编程语言 > 详细

Java 定时循环运行程序

时间:2014-07-31 16:04:26      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:java   os   io   2014   art   代码   ar   时间   

Timer 和 ScheduledExecutorSeruvce 都能执行定时的循环任务,有函数 scheduleAtFixedRate。但是,如果任务运行时间较长,超过了一个周期时长,下一个任务就会被延缓执行。

 

例如代码:

public class ScheduledRunnableTest extends TimerTask {

public void run() {

try {

Thread.sleep(2000);

System.out.println(new Timestamp(System.currentTimeMillis()).toString());

} catch (InterruptedException e) {

e.printStackTrace();

}

}

 

public static void main(String[] args) {

Timer timer = new Timer();

timer.scheduleAtFixedRate(new ScheduledRunnableTest(), 0, 1000);

}

}

运行结果为:

2014-07-31 13:12:30.002

2014-07-31 13:12:32.006

2014-07-31 13:12:34.006

2014-07-31 13:12:36.008

 

 

并不是希望的每秒运行一次。所以得重开线程执行,代码如下:

public class ScehduledThreadTest extends Thread{

public void run() {

try {

Thread.sleep(2000);

System.out.println(new Timestamp(System.currentTimeMillis()).toString());

} catch (InterruptedException e) {

e.printStackTrace();

}

}

 

public static void main(String[] args) {

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

new ScehduledThreadTest().start();

}

}, 

0, 1000);

}

}

这样的结果就是:

2014-07-31 13:15:10.652

2014-07-31 13:15:11.652

2014-07-31 13:15:12.652

 

 

 

Java 定时循环运行程序,布布扣,bubuko.com

Java 定时循环运行程序

标签:java   os   io   2014   art   代码   ar   时间   

原文地址:http://www.cnblogs.com/keepthinking/p/3880589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!