Question

I want,in my mainactivity,to start a thread that does some stuff every x seconds. is this aproach correct?

taken from my oncreate method:

  Thread thread = new Thread()
    {
        @Override
        public void run() {
            try {
                while(true) {
                    sleep(5000);

                    do stuff

    };
    thread.start();

if it's relevant it starts a videoplayer and checks its buffer every 5 seconds.

Was it helpful?

Solution

You can create flexible and effective timer using Java's ExecutorService:

// create executor that consists of 1 thread
final ExecutorService e = Executors.newScheduledThreadPool(1);

// schedule it to execute every 5000 ms starting from now
((ScheduledExecutorService) e).scheduleAtFixedRate(new Runnable(){
     @Override
     public void run() {
         // your repeating task
     }                  
}, 0, 5000, TimeUnit.MILLISECONDS);

This approach is more flexible and, if Java docs don't lie, more precise since it is independent on system clock changes.

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top