Calling a function every 10 minutes
Asked Answered
G

5

31

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?

Georgeanngeorgeanna answered 3/8, 2009 at 6:59 Comment(2)
I think somewhere behind this there's a valid question; that's why I edited it.Calabro
@balpha: you worked some magic there :oRese
M
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);
    }
 }
Marianmariana answered 14/8, 2009 at 15:9 Comment(2)
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 ?Newsreel
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.Secretive
R
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();
    }


}
Rna answered 14/8, 2009 at 15:1 Comment(3)
TimerTask is obsolete, and has been replaced with ExecutorService and associated implementations.Peebles
Really ? Can't find anything saying so. I'd be interested to see your sources. Thanks ! :)Rna
This question/answers confirms skaffman statement: #410432Rna
D
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

Doublebreasted answered 9/7, 2015 at 17:33 Comment(0)
C
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); 
    }
}
Contretemps answered 28/8, 2014 at 9:19 Comment(1)
The class name does not adhere to Java conventions.Poliomyelitis
H
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);
Hornsby answered 29/3, 2019 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.