24

我正在尝试制作一个简单的计时器,在指定的秒数后播放哔声。我设法让它工作,但 TimerTask 在哔声后继续运行。现在我要停止执行吗?这是我的代码:

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

class Alarm {

    public static void main(String[] args) {
        long delay;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a delay in seconds: ");
        delay = scan.nextInt()*1000;

        Timer timer = new Timer();

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Toolkit.getDefaultToolkit().beep();
            }
        };

        timer.schedule(task, delay);
    }
}
4

4 回答 4

54

您需要通过调用以下方法取消定时器

timer.cancel();  // Terminates this timer, discarding any currently scheduled tasks.
timer.purge();   // Removes all cancelled tasks from this timer's task queue.

这将取消任务,所以这样的事情会起作用:

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

class Alarm {

    private static boolean run = true;

    public static void main(String[] args) {
        long delay;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a delay in seconds: ");
        delay = scan.nextInt()*1000;

        final Timer timer = new Timer();

        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(run) {
                   Toolkit.getDefaultToolkit().beep();
                } else {
                   timer.cancel();
                   timer.purge();
                }
            }
        };

        timer.schedule(task, delay);

        // set run to false here to stop the timer.
        run = false;
    }
}
于 2013-04-19T09:03:18.427 回答
6

这对我有用(也使用了 purge() 建议):

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;

class Alarm {

    public static void main(String[] args) {
        long delay;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a delay in seconds: ");
        delay = scan.nextInt()*1000;

        final Timer timer = new Timer();

        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Toolkit.getDefaultToolkit().beep();
                timer.cancel();
                timer.purge();
            }
        };

        timer.schedule(task, delay);
    }
}
于 2013-04-22T07:59:32.467 回答
1

cancel()应该这样做 -cancel停止给定的取消TimerTask/Timer

于 2013-04-19T09:02:08.817 回答
0

isStart = true; // 如果真正的定时器函数 countiue 被调用,否则时间取消
Timer timer = new Timer(); timer.schedule(new TimerClass(), 0, 5000);

class TimerClass extends TimerTask {
    
    public void run() {
        
        if (isStart) {
           yourFunction();
        }else {
            cancel();
        }

    }
}
于 2021-02-08T12:35:25.377 回答