简体   繁体   中英

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 class 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM