Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to perform an action periodically [while an app is running] - Handler?

I'm trying to perform an action periodically. I want to create a new instance of a class after, say, ever 3 seconds. Would it be best to implement this by using a Handler or a Thread? Is there an easier, sort of dopey way I could try? I'm really not good at using threads - I want to learn, but it is more important that I get this to function before worrying about good programming practices.

    new Thread(){
        public void run(){
            //makes sure the player still has 3 lives left
            while(game == false){
                uiCallback.sendEmptyMessage(0);
                try {
                    Thread.sleep(2000); // wait two seconds before drawing the next flower
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } //sleep for 2 seconds
            }
        }
    }.start();
like image 964
Hani Honey Avatar asked Mar 27 '11 20:03

Hani Honey


People also ask

How to run a task periodically in Java?

How to run a task periodically in Java 1 Scheduler Task#N#For this functionality,#N#You should create a class extending TimerTask (available in java.util package). 2 Run Scheduler Task More ...

How to execute code periodically in Java using scheduler?

Write your code in public void run () method that you want to execute periodically. Insert below code in your Main class. 2. Run Scheduler Task A class to run above scheduler task.

How to schedule a task for repeated execution in a Java application?

This post will discuss how to schedule a task for repeated execution in a Java application. 1. Using ScheduledExecutorService ScheduledExecutorServiceis an ExecutorServicethat can schedule commands to run after a given delay, or to execute periodically.


1 Answers

I'm doing something similar in my android app; I update some data in my interface every 10 seconds. There are many ways to do this, but I chose to use a Handler because it's very simple to implement:

Thread timer = new Thread() {
    public void run () {
        for (;;) {
            // do stuff in a separate thread
            uiCallback.sendEmptyMessage(0);
            Thread.sleep(3000);    // sleep for 3 seconds
        }
    }
});
timer.start();
...
private Handler uiCallback = new Handler () {
    public void handleMessage (Message msg) {
        // do stuff with UI
    }
};

As you may know, you cannot run periodic functions like this in the UI thread, because it will block the UI. This creates a new Thread that sends a message to the UI when it is done, so you can update your UI with the new results of whatever your periodic function does.

If you do not need to update the UI with the results of this periodic function, you can simply ignore the second half of my code example, and just spawn a new Thread as shown. Beware, however: if you are modifying variables shared by this new Thread and the UI, you are going to run into problems if you don't synchronize. In general, threading is not an area where you want to ignore "good programming practices" because you'll get strange, non-predictable errors and you'll be cursing your program.

-tjw

like image 179
Travis Webb Avatar answered Nov 06 '22 13:11

Travis Webb