Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this how to schedule a java method to run 1 second later?

Tags:

java

android

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?

like image 333
djcouchycouch Avatar asked Jun 01 '11 17:06

djcouchycouch


People also ask

How do you call a function repeatedly after a fixed time interval in Java?

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.

How do I make my computer wait in Java?

Thread. sleep(1000); This will sleep for one second until further execution. The time is in milliseconds or nanoseconds.


2 Answers

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);
like image 85
mre Avatar answered Oct 26 '22 09:10

mre


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.

like image 37
inazaruk Avatar answered Oct 26 '22 08:10

inazaruk