简体   繁体   English

Java TimerTask取消不起作用

[英]Java TimerTask cancel doesn't work

Trying the TimerTask with ScheduledExecutorService. 使用ScheduledExecutorService尝试TimerTask。 Schedule a task with delay 10 sec, and call task.cancel. 安排任务延迟10秒,然后调用task.cancel。 But the task still run, not sure what happen, and if the cancel method doesn't seems to do any cancelling. 但是任务仍在运行,不确定会发生什么,并且如果cancel方法似乎没有执行任何取消操作。 Please help. 请帮忙。

package xxx.xxx;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Tester {

    static class OrderWaveTask extends TimerTask{
        public void run() {
            System.out.println("hi");
        }
    }

    public static void main(String[] args) {

        ScheduledExecutorService orderWaveTP = Executors.newScheduledThreadPool(3);
        TimerTask task = new Tester.OrderWaveTask();
        orderWaveTP.schedule(task, 10, TimeUnit.SECONDS);
        System.out.println("cancelling task: "+ task.cancel());
    }

}

You should use ScheduledFuture to cancel the task. 您应该使用ScheduledFuture取消任务。 Change your code to following should make it work. 将您的代码更改为以下代码即可使其正常工作。

ScheduledFuture<?> future = orderWaveTP.schedule(task, 10, TimeUnit.SECONDS);
System.out.println("cancelling task: "+ future.cancel(false));

The TimerTask is meant to be used with a Timer class in order to schedule executions and support cancellation. TimerTask旨在与Timer类一起使用,以计划执行并支持取消。

When you schedule a TimerTask via an Executor, you're really just telling the executor to run a Runnable, and control is performed by the Executor; 当通过Executor调度TimerTask时,实际上只是在告诉执行程序运行Runnable,而控制由Executor执行。 it has no idea that you're running a TimerTask, so the TimerTask functions have no effect. 它不知道您正在运行TimerTask,因此TimerTask函数无效。

Your choices would be to use a Timer instead of an ExecutorService, or use the ExecutorService methods to cancel execution. 您的选择是使用计时器而不是ExecutorService,或使用ExecutorService方法取消执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM