How to schedule a function every defined time with the option to change this time? I found that I can do it using timer & timerTask or handler. The problem that it dosen't repeats the time I defined, it repeats randomaly...
runnable = new Runnable() {
@Override
public void run() {
//some action
handler.postDelayed(this, interval);
}
};
int hours = settings.getIntervalHours();
int minutes = settings.getIntervalMinutes();
long interval = (hours * 60 + minutes) * 60000;
changeTimerPeriod(interval);
private void changeTimerPeriod(long period) {
handler.removeCallbacks(runnable);
interval = period;
runnable.run();
}
Use a Handler object in the onCreate
method. Its postDelayed
method causes the Runnable
parameter to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 millis in this example).
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.os.Handler customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable()
{
public void run()
{
//write here whaterver you want to repeat
customHandler.postDelayed(this, 1000);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With