views:

397

answers:

2

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?

A: 
import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

public class ClassExecutingTask {

    long delay = 10*1000; // delay in ms : 10 * 1000 ms = 10 sec.
    LoopTask task = new LoopTask();
    Timer timer = new Timer("TaskName");

    public void start() {
    timer.cancel();
    timer = new Timer("TaskName");
    Date executionDate = new Date(); // no params = now
    timer.scheduleAtFixedRate(task, executionDate, delay);
    }

    private class LoopTask extends TimerTask {
    public void run() {
        System.out.println("This message will print every 10 seconds.");
    }
    }

    public static void main(String[] args) {
    ClassExecutingTask executingTask = new ClassExecutingTask();
    executingTask.start();
    }


}
Silence
Just change the delay....
Silence
TimerTask is obsolete, and has been replaced with ExecutorService and associated implementations.
skaffman
Really ? Can't find anything saying so. I'd be interested to see your sources. Thanks ! :)
Silence
+1  A: 

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);
    }
 }
Tim