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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With