0

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.

1
  • I'm writing a simple program in Java and not using Swing. So,, is there anyway to call getVal() without putting it inside run() or using the run() at all? Thanks again. Commented Sep 28, 2011 at 18:26

4 Answers 4

5

Old Way

java.util.Timer


New (and preferred) Way

java.util.concurrent.Executors


Implementation

More specifically, use the ScheduledExecutorService class.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

Check out the Timer class.

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

1 Comment

It always worked well for me, but there's also the more "modern" API ScheduledExecutorService and ScheduledFuture, which does the trick as well.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.