30

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769

5 Answers5

31

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
  • 19,793
  • 8
  • 70
  • 95
  • I used your code from main. But when the task reached time limit, the program does not exit. How is it possible to make that the program stops when the task is done ? – Itération 122442 Dec 20 '19 at 15:07
  • 1
    Runs like a charm. Might be worth mentioning that scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); the first 10 is how long to wait before sending first beep. second 10 is how long to wait for each next beep. and 60*60 is how long it will run for. – Slobodan Margetić Dec 19 '20 at 19:10
18
import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

public class ClassExecutingTask {

    long delay = 10 * 1000; // delay in milliseconds
    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();
    }


}
Jemar Jones
  • 1,491
  • 2
  • 21
  • 27
Philippe Carriere
  • 3,712
  • 4
  • 25
  • 46
14

Try this. It will repeat the run() function every set minutes. To change the set minutes, change the MINUTES variable

int MINUTES = 10; // The delay in minutes
Timer timer = new Timer();
 timer.schedule(new TimerTask() {
    @Override
    public void run() { // Function runs every MINUTES minutes.
        // Run the code you want here
        CLASSB.funcb(); // If the function you wanted was static
    }
 }, 0, 1000 * 60 * MINUTES);
    // 1000 milliseconds in a second * 60 per minute * the MINUTES variable. 

Don't forget to do the imports!

import java.util.Timer;
import java.util.TimerTask;

For more info, go here:

http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

Fnaf Server
  • 161
  • 1
  • 10
4
public class datetime {

    public String CurrentDate() {

        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String currentTime = sdf.format(dt);
        return currentTime;

    }

    public static void main(String[] args) {
        class SayHello extends TimerTask {

            datetime thisObj = new datetime();

            public void run() {
                String todaysdate = thisObj.CurrentDate();
                System.out.println(todaysdate);
            }
        }
        Timer timer = new Timer();
        timer.schedule(new SayHello(), 0, 5000); 
    }
}
James Fenn
  • 109
  • 1
  • 14
overflow
  • 145
  • 8
4

Solution with Java 8

ClassB b = new ClassB();    
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
    b.funb();
};
executor.scheduleWithFixedDelay(task, 0, 10, TimeUnit.MINUTES);
byteprom
  • 541
  • 4
  • 4