如何在处理程序线程中运行重复性任务?

时间:2019-01-29 11:27:41

标签: android multithreading

如何在指定的时间延迟内在Handler Thread中重复执行相同的任务,以及如何在Main Thread中更新视图。

我需要在30秒的间隔内在后台线程中重复运行此代码,并在Main线程中更新结果,因为如果在此处执行此操作将阻塞UI线程。

final Handler handler = new Handler();

    handler.post(new Runnable() {
        @Override
        public void run() {
            int hours = mSeconds/3600;
            int mins = (mSeconds%3600)/60;
            int secs = mSeconds%60;

            String timeElapsed = "";
            if (hours>0){
                timeElapsed = String.format("%02d:%02d",hours,mins);
            }else{
                timeElapsed = String.format("%02d:%02d",mins,secs);
            } 
// there are some other networking stuff also which will be executed here            

            if(mRunning){
                mSeconds++;
            }
// update the view as well

            handler.postDelayed(this, 3000);

        }
    });

2 个答案:

答案 0 :(得分:0)

当您希望它执行时。

mToastRunnable.run()

功能

private val mToastRunnable = object : Runnable {
    override fun run() {
        Handler().postDelayed({
        // Do Something.
        }, 7000) //Delay in the running of this function
        mHandler.postDelayed(this, 10000)  //Iteration of 10 Sec 
    }
}

答案 1 :(得分:0)

请勿为此使用Handler-不适合。如果没有更多信息,我建议您使用ExecutorService

Executors.newSingleThreadScheduledExecutor().schedule(() -> {
    //Run scheduled background task here. Call onto the main thread with 
    // new Handler(Looper.getMainLooper()).post(() -> { /*task to execute */ });        
}, 30, TimeUnit.SECONDS);

如果您想知道已经花费了多少时间,RxJava是另一个不错的选择。此语法适用于RxJava 1.x,但与RxJava 2.x非常相似(我认为您只是将Observable换成Flowable):

Observable.interval(30, TimeUnit.SECONDS)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(interval -> { /* Task. "Interval" is the time elapsed so far */});