Skip to content Skip to sidebar Skip to footer

Is This How To Schedule A Java Method To Run 1 Second Later?

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 ru

Solution 1:

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:

Handlerhandler=newHandler();
handler.postDelayed(newRunnable()
{
     @Overridepublicvoidrun()
     {
         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.

Solution 2:

Instead of a Timer, I'd recommend using a ScheduledExecutorService

finalScheduledExecutorServiceexec= Executors.newScheduledThreadPool(1);

exec.schedule(newRunnable(){
    @Overridepublicvoidrun(){
        MyMethod();
    }
}, 1, TimeUnit.SECONDS);

Solution 3:

If you are not in UI thread, consider adding a very simple:

try
{
  Thread.sleep( 1000 );
}//trycatch( Exception ex)
{ ex.printStackTrace(); }//catch//call your method

Solution 4:

ScheduledExecutorService or AsyncTask for UI related.

Note that if you are to update UI, that code should be posted to UI thread. as in Processes and Threads Guide

finalBitmapbitmap= loadImageFromNetwork("http://example.com/image.png");
        mImageView.post(newRunnable() {
            publicvoidrun() {
                mImageView.setImageBitmap(bitmap);
            }
        });

There is also nice postDelayed method in View

    mImageView.postDelayed(newRunnable(){
        @Overridepublicvoidrun() {
            mImageView.setImageResource(R.drawable.ic_inactive);
        }
    }, 1000);

that will update UI after 1 sec.

Post a Comment for "Is This How To Schedule A Java Method To Run 1 Second Later?"