开发者

Schedule a task after a specific interval in Java

I've got a class

class A {
     int a=0;
     public int getVal() {
         return a;
     }
}

and I've to execute the function getVal periodically. How do I do it from another c开发者_JAVA百科lass b? Thanks.


Old Way

java.util.Timer


New (and preferred) Way

java.util.concurrent.Executors


Implementation

More specifically, use the ScheduledExecutorService class.


Various potential problems with java.util.Timer are listed in section 6.2.5 of "Java Concurrency in Practice." For example:

  • Timer behaves poorly if a TimerTask takes too long to run.
  • Timer behaves poorly if a TimerTask throws an unchecked exception.

The authors of that book concluded that "there is little reason to use Timer in Java 5.0 or later."

Instead, they recommend using a ScheduledExecutorService. You can construct one either via the ScheduledThreadPoolExecutor constructor or via the newScheduledThreadPool factory methods in Executors. The later option is better.


Check out the Timer class.

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html


Simply just give a look on Threads in java. you can make this class runnable, and execute the function periodically, and the delay can be generated using the sleep() function. Otherwise you can make the calling function runnable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜