DEV Community

Cover image for Easy reoccurring task scheduler in Android
Ali Alp
Ali Alp

Posted on • Updated on

Easy reoccurring task scheduler in Android

In mobile development often there is a need to run a method couple of times, or on a fixed schedule , like playing an animation or fetching data every some seconds, according to the Android's best practices, it is recommended to use the Handler object, the following snippet can come in handy when you have a lot of reoccurring tasks

import android.os.Bundle;

public interface IReoccurringTask {
    void run(Bundle bundle);
}
Enter fullscreen mode Exit fullscreen mode
import android.os.Bundle;
import android.os.Handler;

public class ReoccurringTaskScheduler {

    private Handler handler = new Handler();
    private Runnable runnable;
    private IReoccurringTask reoccurringTask;

    private ReoccurringTaskScheduler(){}

    public ReoccurringTaskScheduler(IReoccurringTask reoccurringTask) {
        this.reoccurringTask=reoccurringTask;
    }

    public void Schedule(long initDelay, final long interval) {

        runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    reoccurringTask.run(null);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    handler.postDelayed(this, interval);
                }
            }
        };
        handler.postDelayed(runnable, initDelay);
    }

    public void Schedule(final Bundle bundle, long initDelay, final long interval) {

        runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    reoccurringTask.run(bundle);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    handler.postDelayed(this, interval);
                }
            }
        };
        handler.postDelayed(runnable, initDelay);
    }

    public void cancel() {
        if (runnable != null)
            handler.removeCallbacks(runnable);
    }
}
Enter fullscreen mode Exit fullscreen mode

and you can define your custom logic like this

private class ReoccurringLogicClass implements IReoccurringTask{

    @Override
    public void run(Bundle bundle) {

        //reoccurring logic
    }


}
Enter fullscreen mode Exit fullscreen mode

and then use it like this

ReoccurringTaskScheduler rTask=
    new ReoccurringTaskScheduler(new ReoccurringLogicClass()).Schedule(1000,2000);
Enter fullscreen mode Exit fullscreen mode

and cancel it like this

rTask.cancel();
Enter fullscreen mode Exit fullscreen mode

Happy coding :)

Top comments (0)