package net.openmob.mobileimsdk.android.utils;

import android.os.Handler;
import android.util.Log;

public abstract class MBSimpleTimer {
    private Handler handler = null;

    private Runnable runnable = null;

    private int interval = -1;

    public MBSimpleTimer(int interval) {
        this.interval = interval;
    }

    public void init() {
        this.handler = new Handler();
        this.runnable = (() -> {
            try {
                doAction();
            } catch (Exception e) {
                Log.w(MBSimpleTimer.class.getSimpleName(), e);
            }
            this.handler.postDelayed(this.runnable, this.interval);
        });
    }

    public void start(boolean immediately) {
        stop();
        onStart();
        this.handler.postDelayed(this.runnable, immediately ? 0L : this.interval);
    }

    protected void onStart() {}

    public void stop() {
        this.handler.removeCallbacks(this.runnable);
        onStop();
    }

    protected void onStop() {}

    protected abstract void doAction();
}
