Home » Android » java – Android: Standard way to make a thread run every second

java – Android: Standard way to make a thread run every second

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m trying to run a Thread class every second. I cant use Runnable. I tried in the following way, but its throwing StackOverflowException. Can anyone please let me know a standard method to make a thread class run every second.

public class A extends Thread {

    public void run() {
       //do my stuff
      sleep(1*1000,0);
      run();
    }
}
How to&Answers:

Use Timer‘s schedule() or scheduleAtFixedRate() (difference between these two) with TimerTask in the first argument, in which you are overriding the run() method.

Example:

Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    @Override
    public void run()
    {
        // TODO do your thing
    }
}, 0, 1000);

Your example causes stack overflow, because it’s infinite recursion, you are always calling run() from run().

Answer:

Maybe you want to consider an alternative like ScheduledExecutorService

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

/*This schedules a runnable task every second*/
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
  public void run() {
    DoWhateverYouWant();
  }
}, 0, 1, TimeUnit.SECONDS);

Answer:

final ExecutorService es = Executors.newCachedThreadPool();
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable()
{
    @Override
    public void run()
    {
        es.submit(new Runnable()
        {
            @Override
            public void run()
            {
                // do your work here
            }
        });
    }
}, 0, 1, TimeUnit.SECONDS);