Android: standard way to make a thread run every second

I try to run the Thread class every second. I can not use Runnable . I tried as follows, but its throwing is a StackOverflowException . Can someone please let me know the standard method to run the thread class each time.

 public class A extends Thread { public void run() { //do my stuff sleep(1*1000,0); run(); } } 
+6
source share
3 answers

Use Timer schedule() or scheduleAtFixedRate() (the difference between the two ) with TimerTask in the first argument, in which you override 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 a stack overflow because it is infinitely recursive, you always call run() from run() .

+15
source

You might 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); 
+3
source
 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); 
+2
source

Source: https://habr.com/ru/post/946313/


All Articles