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

Stop a TimerTask without stopping the Timer

我有一个 Timer,我使用方法 scheduleAtFixedRate 以一定的固定速率为其安排任务。问题是,在一些操作之后,我想 finish/cancel 这个之前安排的任务。

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

你们知道怎么做吗?

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

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

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

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

TimerTask 上调用 cancel() 不会停止 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();