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