Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method at a time interval

Do Java/Android have any constructs available for running a method within a class at some time interval?

I am aware of the Scheduler and Timer classes but I need to avoid instantiating another class. The method must not run in another separate thread. Running an AsyncTask or Handler results in a separate thread.

like image 789
Johann Avatar asked Dec 08 '25 06:12

Johann


1 Answers

The method must not run in another separate thread

Because of this requirement you only have one reasonable solution, you must wait in your own thread, like this:

for (int i = 0; i < 100; i++) {
    long intervalInMs = 1000; // run every second
    long nextRun = System.currentTimeMillis() + intervalInMs;
    callAMethod();
    if (nextRun > System.currentTimeMillis()) {
        Thread.sleep(nextRun - System.currentTimeMillis());
    }
}

Note, that if the method call takes longer time than you want to wait, it will not call twice (because you only have one Thread) You can detect it by writing an else clause to the if, and make some modifications (e.g. increase the intervalInMs);

like image 56
gaborsch Avatar answered Dec 09 '25 18:12

gaborsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!