定时器异步任务不能按预期工作 [英] Timer in Asynchronous Task does not work as expected

查看:106
本文介绍了定时器异步任务不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行异步任务内的一个任务,我设置的时间限制为15秒,但有时也命中3分,5到10秒。我不知道怎么回事错了。如果有人可以帮助我最好的AP preciate它,谢谢!

 公共无效callAsynchronousTask(){
    最后的处理程序处理程序=新的处理程序();
    定时器定时器=新的Timer();
    TimerTask的doAsynchronousTask =新的TimerTask(){
        @覆盖
        公共无效的run(){
            handler.post(新的Runnable(){
                公共无效的run(){
                    尝试{                    //我的任务                    }赶上(例外五){                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask,15000,15000);
}


解决方案

我已经计时器,如果我们想要然后停止myTimer.cancel()做了计算适当的时间和。并感谢@PearsonArtPhoto为参考:)

 定时器myTimer;myTimer =新的Timer();
    myTimer.schedule(新的TimerTask(){
        @覆盖
        公共无效的run(){
        //我的任务
        }    },0,10000);

I execute one task inside an asynchronous task and I set the time limit to 15 seconds, but sometimes it hits 3, 5 and 10 seconds. I don't know whats going wrong. If anyone can help I'd appreciate it, thanks!

public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {

                    // My Task

                    } catch (Exception e) {

                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 15000, 15000);
}

解决方案

I have done by timer it calculate proper time and if we want stop then myTimer.cancel(). And thanks @PearsonArtPhoto for referring :)

Timer myTimer;

myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
        // my task
        }

    }, 0, 10000);

这篇关于定时器异步任务不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆