我想在一个类中使用一个函数来启动和停止使用布尔值链接到int值的计时器。因此,例如,如果我启动了一个int为0的计时器,那么这将是timer0,如果它是3,那么timer3等等。在Java中停止计时器事件
我遇到的问题是计时器似乎开始确定,但是当我向他们发送一个假布尔来阻止他们时,他们将继续运行,因此我需要知道如何正确阻止他们。
在Class.java代码:
public void Event(final int value, boolean run, int time){
if(run){
System.out.println(run);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// The needed code will go here
System.out.println(value + " Event run");
}
}, 0, time); // Every second
} else {
}
}
然后我Main.java代码:
System.out.println("Start Timer 0 Event");
r.Event(0, true, 1000);
System.out.println("Start Timer 1 Event");
r.Event(1, true, 250);
System.out.println("Start Timer 2 Event");
r.Event(2, true, 250);
r.Event(0, false, 1000); // Not Working as i need
System.out.println("Stop Timer 0 Event");
基本上我只是想有套活动得到重复一次集直到我阻止他们的时间量,并且可能有许多人在一起运行。如果定时器不是这样做的最好方法,那么替代方案会很好,但它需要按照描述的相同方式工作。
根据要求,这里是我的计时器的可运行代码。
MyClass.java:
package com.z;
import java.awt.*;
import java.util.*;
import java.util.TimerTask;
public class MyClass {
////////////////////////////////////////////////////////////
//Name: Event (BROKEN)
////////////////////////////////////////////////////////////
public void Event(final int value, boolean run, int time){
Timer timer = new Timer("" + value, true);
if(run){
System.out.println(run);
timer.schedule(new TimerTask() {
public void run() {
// Code here
System.out.println(value + " Event run");
}
}, 0, time); // Every second
}
if (!run) {
timer.cancel();
}
}
}
Example.java:
package com.z;
import java.awt.*;
import java.awt.event.*;
public class Example {
public static void main(String[] args) {
MyClass r = new MyClass();
////////////////////////////////////////////////////////////
// Event (BROKEN)
////////////////////////////////////////////////////////////
System.out.println("Start Timer 0 Event");
r.Event(0, true, 1000);
System.out.println("Start Timer 1 Event");
r.Event(1, true, 250);
r.Event(0, false, 1000);
System.out.println("Stop Timer 0 Event");
}
}
你可以发布一个简短的,完整的可运行的代码不适合你的例子吗? – 2012-08-02 12:12:34
这不是可运行的代码(或者至少不容易运行)。你可以添加可以复制/粘贴并轻松运行的主要方法吗?请使用代码编辑您的帖子或添加到pastebin。 – 2012-08-02 12:37:36
一旦你在Event方法中启动定时器,你就无法取消同一个定时器,因为它是一个局部变量。为什么不直接从Event方法返回计时器(可能需要重命名该方法),而不是运行参数。然后,当你准备好停止那个计时器时,只需对它停止。 – 2012-08-02 13:24:45