Calling a function every 10 minutes

user149537 picture user149537 · Aug 3, 2009 · Viewed 59.6k times · Source

I'm not an expert, just a beginner. So I kindly ask that you write some code for me.

If I have two classes, CLASS A and CLASS B, and inside CLASS B there is a function called funb(). I want to call this function from CLASS A every ten minutes.

You have already given me some ideas, however I didn't quite understand.

Can you post some example code, please?

Answer

Tim picture Tim · Aug 14, 2009

Have a look at the ScheduledExecutorService:

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }