在不停止Timer的情况下停止TimerTask

时间:2016-09-06 12:46:05

标签: java android timer timertask

我有一个Timer,我使用方法scheduleAtFixedRate以固定费率为其安排任务。问题是,在执行某些操作后,我想完成/取消之前安排的此任务。

我知道我可以使用.cancel().purge() ,但这会取消/完成我的计时器,这是我不想要的。我只想完成任务。

你们有谁知道怎么做?

这是我的代码(我将Timer创建为类的字段)

receiveTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            int fileSize=(int)fileSizeToReceive;
            int actual= totalReceived;

            ((Notification.Builder) mBuilderReceive).setContentText("Receiving  "+actualNameToReceive);
            ((Notification.Builder) mBuilderReceive).setProgress(fileSize, actual, false);
            mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification());
        }
    },0,500);//delay, interval

2 个答案:

答案 0 :(得分:1)

boolean isStop = false;

 receiveTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
         public void run() {

          if(!isStop){

            int fileSize=(int)fileSizeToReceive;
            int actual= totalReceived;

            ((Notification.Builder) mBuilderReceive).setContentText("Receiving  "+actualNameToReceive);
            ((Notification.Builder) mBuilderReceive).setProgress(fileSize, actual, false);
            mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive).getNotification());
          }
        }
    },0,500);//delay, interval

当您不想执行代码集isStop = true

答案 1 :(得分:1)

只需保留对TimerTask的引用,这样您就可以随时拨打cancel()

cancel()上拨打TimerTask不会停止Timer

例如,声明您的任务:

TimerTask task;

初始化并安排它:

task = new TimerTask() {
    @Override
    public void run() {
        int fileSize=(int)fileSizeToReceive;
        int actual= totalReceived;

        ((Notification.Builder) mBuilderReceive)
            .setContentText("Receiving  "+actualNameToReceive);
        ((Notification.Builder) mBuilderReceiver)
            .setProgress(fileSize, actual, false);
        mNotifyManager.notify(id, ((Notification.Builder) mBuilderReceive)
            .getNotification());
    }
};

receiveTimer.scheduleAtFixedRate(task, 0, 500);

要停止它,您只需在任务实例上调用cancel()

task.cancel();