How do you use a TimerTask to run a thread?

2019-01-06 18:23发布

I'm struggling to find documentation for the TimerTask function on Android. I need to run a thread at intervals using a TimerTask but have no idea how to go about this. Any advice or examples would be greatly appreciated.

3条回答
叼着烟拽天下
2楼-- · 2019-01-06 18:33

This is perfect example for timer task.

Timer timerObj = new Timer();
TimerTask timerTaskObj = new TimerTask() {
    public void run() {
       //perform your action here
    }
};
timerObj.schedule(timerTaskObj, 0, 15000);
查看更多
走好不送
3楼-- · 2019-01-06 18:34

You use a Timer, and that automatically creates a new Thread for you when you schedule a TimerTask using any of the schedule-methods.

Example:

Timer t = new Timer();
t.schedule(myTimerTask, 1000L);

This creates a Timer running myTimerTask in a Thread belonging to that Timer once every second.

查看更多
贪生不怕死
4楼-- · 2019-01-06 18:39

I have implemented something like this and it works fine:

    private Timer mTimer1;
    private TimerTask mTt1;
    private Handler mTimerHandler = new Handler();

    private void stopTimer(){
        if(mTimer1 != null){
            mTimer1.cancel();
            mTimer1.purge();
        }
    }

    private void startTimer(){
        mTimer1 = new Timer();
        mTt1 = new TimerTask() {
            public void run() {
                mTimerHandler.post(new Runnable() {
                    public void run(){
                        //TODO
                    }
                });
            }
        };

        mTimer1.schedule(mTt1, 1, 5000);
    }
查看更多
登录 后发表回答