Johann
Johann

Reputation: 29867

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.

Upvotes: 3

Views: 1937

Answers (4)

gaborsch
gaborsch

Reputation: 15748

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

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83517

If you really must do this in the same thread without blocking, one possible solution is to do some kind of polling. I imagine code which periodically calculates how much time has passed since the last time the method fired. If the configured time period has elapsed, then fire the method again.

This kind of solution seems complex to implement. How often do you execute the polling code? How do you execute the polling code within the logic of the rest of the app that is likely continuing to execute in the mean time? These are only the technical challenges that come immediately to mind. I'm sure there are others. With this in mind, I think the better solution is to rethink your restrictions. Why do you want to do this in the same thread? You should think hard about your reasons and consider using a separate thread (whether you roll it yourself with Timer or you use the Android platform to manage it for you with AlarmManager.

Upvotes: 0

noni
noni

Reputation: 2947

Create a custom Timer that receives a Listener, then when your time has elapsed, send the callback to the object that has created the Timer in his thread.

This will create a new Thread for the Timer, but the method you want to execute, will be executed on the original's object thread

Upvotes: 0

Booger
Booger

Reputation: 18725

You need to use the AlarmManager for this.

Check this SO for a good overview: Android: How to use AlarmManager

I would not try to manage this within your own thread, but let the Android framework handle this for you. Not sure why you need it to run in the same Thread.

Upvotes: 0

Related Questions