Android - Run a thread repeatingly within a timer

北城以北 提交于 2019-11-27 15:06:11
Tuna Karakasoglu

Just simply use below snippet

private final Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    public void run() {
         //
         // Do the stuff
         //

         handler.postDelayed(this, 1000);
    }
};
runnable.run();

To stop it use

handler.removeCallbacks(runnable);

Should do the trick.

sarkolata

Thanks to everyone, I fixed this issue with using Timer.

timer = new Timer();
timer.scheduleAtFixedRate(
    new java.util.TimerTask() {
        @Override
        public void run() {
            for (int i = 0; i < server_amount; i++) {

                servers[i] = "Updating...";
                handler.sendEmptyMessage(0);
                new MyThread(i).start();
            }
        }
    },
2000, 5000);

I would think to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html

If checkbox is on call method where

AlarmManager alarmManager = (AlarmManager)SecureDocApplication.getContext()
    .getSystemService(Context.ALARM_SERVICE);
PendingIntent myService = PendingIntent.getService(context, 0, 
                new Intent(context, MyService.class), 0);

long triggerAtTime = 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, 5000 /* 5 sec*/, 
                myService);

If checkbox is off cancel alarm manager

alarmManager.cancel(myService);

Use a CountDownTimer. The way it works is it will call a method on each tick of the timer, and another method when the timer ends. At which point you can restart if needed. Also I think you should probably be kicking off AsyncTask rather than threads. Please don't try to manage your own threads in Android. Try as below. Its runs like a clock.

 CountDownTimer myCountdownTimer =    new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     // Kick off your AsyncTask here.
 }

 public void onFinish() {
     mTextField.setText("done!");
     // the 30 seconds is up now so do make any checks you need here.
 }
 }.start();

"[ScheduledThreadPoolExecutor] class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required."

per...

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

It's not much more than the handler, but has the option of running exactly every so often (vice a delay after each computation completion).

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


...


final int THREAD_POOL_SIZE = 10;
final int START_DELAY = 0;
final int TIME_PERIOD = 5;
final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

ScheduledThreadPoolExecutor pool;

Runnable myPeriodicThread = new Runnable() {
    @Override
    public void run() {
        refreshAllServers();
    }
};


public void startTimer(){

    pool.scheduleAtFixedRate(myPeriodicThread,
            START_DELAY,
            TIME_PERIOD,
            TIME_UNIT);

}

public void stopTimer(){

    pool.shutdownNow();

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!