I would suggest you do this with RxJava. In jus a few lines you will be able to handle delays and not have to worry about handlers and cancelling this. This would also save it a lot of time if you have to create multiple handlers.
This will create a subscriber that will invoke the onNext() of the intervalSubscriber when an observable that this subscriber is subscribed to emits something.
// Set up a subscriber once. Setting up the subscriber
private Subscriber<Long> intervalSubscriber = new Subscriber<Long> () {
@Override
public void onCompleted() {
//Wrap up things as onCompleted is called once onNext() is over
}
@Override
public void onError(Throwable e) {
//Keep an eye open for this. If onCompleted is not called, it means onError has been called. Make sure to override this method
}
@Override
public void onNext(Long aLong) {
// aLong will be from 0 to 1000
// Yuor code logic goes here
// If you want to run this code just once, just add a counter and call onComplete when the counter runs the first time
}
}
Let's go with with creating the observable that will emit.
//Setting up the Observable. This will make runThisOnInterval observable emit every 5 seconds on Computation Threadpool created and managed by RxJava.
private Observable<Long> runThisOnInterval = Observable.interval(5000, TimeUnit.MILLISECONDS, Schedulers.computation());
Ok, so we are all set now. All we need to do now is to subscriber intervalSubscriber to runThisOnInterval observable so that the observable can start producing and the subscriber can consume.
Simple call to subscribe()
will start the emissions and it's NOT done on the main thread which gives me a lot of flexibility.
runThisOnInterval.subscribe(intervalSubscriber);