我想在一個類中使用一個函數來啓動和停止使用布爾值鏈接到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