Java 定时器

标签 java timer

我正在尝试使用计时器来安排应用程序中的重复事件。但是,我希望能够实时调整事件触发的时间段(根据用户输入)。

例如:

public class HelperTimer extends TimerTask
{
    private Timer timer;
    //Default of 15 second between updates
    private int secondsToDelay = 15;

    public void setPeriod(int seconds)
    {
        this.secondsToDelay = seconds;
        long delay = 1000; // 1 second
        long period = 1000*secondsToDelay; // seconds
        if (timer != null) 
        {
            timer.cancel();
        }
        System.out.println(timer);
        timer = new Timer();
        System.out.println(timer);
        timer.schedule(this, delay, period);
    }
    public int getPeriod()
    {
        return this.secondsToDelay;
    }
}

然后我启动这个类的一个新实例并调用它的设置周期函数。但是,当我这样做时,我得到一个非法状态异常。你可以看到 System.out.println(timer);在那里,因为我正在检查,是的,它们是两个不同的计时器......那么为什么当我尝试在全新的 Timer 实例上运行调度调用时会收到 IllegalStateException !?!?!?!

java.util.Timer@c55e36
java.util.Timer@9664a1
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Task already scheduled or cancelled
    at java.util.Timer.sched(Unknown Source)
    at java.util.Timer.schedule(Unknown Source)
    at HelperTimer.setPeriod(HelperTimer.java:38)

最佳答案

您不能像在这里一样重用 TimerTask。

Timer 的相关部分:

private void sched(TimerTask task, long time, long period) {
    if (time < 0)
        throw new IllegalArgumentException("Illegal execution time.");

    synchronized(queue) {
        if (!thread.newTasksMayBeScheduled)
            throw new IllegalStateException("Timer already cancelled.");

        synchronized(task.lock) {
            //Right here's your problem.
            //  state is package-private, declared in TimerTask
            if (task.state != TimerTask.VIRGIN)
                throw new IllegalStateException(
                    "Task already scheduled or cancelled");
            task.nextExecutionTime = time;
            task.period = period;
            task.state = TimerTask.SCHEDULED;
        }

        queue.add(task);
        if (queue.getMin() == task)
            queue.notify();
    }
}

您需要重构代码,以便创建一个新的 TimerTask,而不是重复使用一个。

关于Java 定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1041675/

相关文章:

java - 我可以将依赖的 jar 文件直接包含在 jboss EAP 7.3 容器中吗?

java - 调整大小时多线程环境中的 HashMap

java - 更改 SWT 表/树中的行高

c# - 在指定时间引发事件

swift - 使用 XCTest 在 Xcode 中测试定时器

java - 条件 DynamoDb 查询

Java 使用 subList()

android - 如何实现执行 AsyncTask 的 Timer/TimerTask? (安卓)

jquery - Codeigniter 和 ajax 中的计时器

python - sys.exit(0) 是退出/终止 python 线程的有效方法吗?