Java计时器

编程入门 行业动态 更新时间:2024-10-27 00:28:57
本文介绍了Java计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm trying to use a timer to schedule a recurring event in an application. However, I want to be able to adjust the period at which the event fires in real time (according to the users input).

例如:

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实例上运行计划调用时,为什么会出现IllegalStateException!?!?!?!

I then start a new instance of this class and call its set period function. However, when I do that, I get an Illegal state exception. You can see the System.out.println(timer); in there because I'm checking, and yep sure enough, they are two different timers... so why am I getting an IllegalStateException when I try to run a schedule call on a brand new Timer instance!?!?!?!

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。

You can't reuse a TimerTask as you're doing here.

计时器:

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,而不是重新使用它。

You'll need to refactor your code so that you create a new TimerTask, rather than re-using one.

更多推荐

Java计时器

本文发布于:2023-11-09 06:21:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!