定时器取消方法

时间:2016-01-10 00:18:19

标签: java timer

我对类java.util.Timer有疑问,特别是它的cancel()方法。

如果我编写这样的代码并将其调用4000次(例如),它就不会停止执行,我应该猜测该事件:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    private int id = ++TimerTest.counter;
    @Override
    public void run() {
        if(counter % 100 == 0)
            System.out.println("TimerTest #" + id + "\nI'm doing task: " + task);
        if(counter == 4000 && canceled == true){
            System.out.println("Canceling...");
            timer.cancel();
        }
    }
}, 0);

但不是上面的脚本,我可以将其改为:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    private int id = ++TimerTest.counter;
    @Override
    public void run() {
        if(counter % 100 == 0)
            System.out.println("TimerTest #" + id + "\nI'm doing task: " + task);
        if(counter == 4000 && canceled == true){
            System.out.println("Canceling...");
        }
    }
}, 0);
timer.cancel();

我一直在寻找同样的问题描述,但我没有遇到任何特别的问题:)

1 个答案:

答案 0 :(得分:1)

问题似乎在于您似乎正在调用Timer 4000次。相反,你应该有1个计时器,并安排一个时间段。拨打

public void schedule(TimerTask task, long delay, long period)

方法而不是

public void schedule(TimerTask task, long delay)

以下是正确使用的示例:

import java.util.Timer;
import java.util.TimerTask;

public class TimerTest {

    private static int counter = 0;

    private void doTimer() throws InterruptedException {
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                counter ++;
                System.out.println("TimerTest #" + counter + " I'm doing task");    
            }
        }, 0,1000);

        //Sleep for 10 seconds before cancelling the timer
        Thread.currentThread().sleep(10000);
        System.out.println("Timer cancelled");
        timer.cancel();
    }

    public static void main(String args[]) throws InterruptedException {
        new TimerTest().doTimer();
    }

}

这会在10秒后停止计时器:

TimerTest #1 I'm doing task
TimerTest #2 I'm doing task
TimerTest #3 I'm doing task
TimerTest #4 I'm doing task
TimerTest #5 I'm doing task
TimerTest #6 I'm doing task
TimerTest #7 I'm doing task
TimerTest #8 I'm doing task
TimerTest #9 I'm doing task
TimerTest #10 I'm doing task
Timer cancelled