In my method, I want to call another method that will run 1 second later. This is what I have.
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
MyMethod();
Log.w("General", "This has been called one second later");
timer.cancel();
}
}, 1000);
Is this how it's supposed to be done? Are there other ways to do it since I'm on Android? Can it be repeated without any problems?
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.
Thread. sleep(1000); This will sleep for one second until further execution. The time is in milliseconds or nanoseconds.
Instead of a Timer
, I'd recommend using a ScheduledExecutorService
final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.schedule(new Runnable(){
@Override
public void run(){
MyMethod();
}
}, 1, TimeUnit.SECONDS);
There are several alternatives. But here is Android specific one.
If you thread is using Looper
(and Normally all Activity
's, BroadcastRecevier
's and Service
's methods onCreate
, onReceive
, onDestroy
, etc. are called from such a thread), then you can use Handler
. Here is an example:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
myMethod();
}
}, 1000);
Note that you do not have to cancel anything here. This will be run only once on the same thread your Handler was created.
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