I am trying to use a single function in a class that will start and stop timers which are linked to int values using a boolean. So for example if I started a timer with a int of 0 then that would be timer0 and if it was 3 then timer3 and so on.
The problem I am having is that the timers seem to start ok but when I send them a false bool to stop them they will keep running so I need to know how I can stop them correctly.
In the Class.java the code is:
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 {
}
}
Then for my Main.java the code is:
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");
Basically I just want to have sets of events get repeated every set amount amount of time until I stop them and there could be many run together. If timers are not the best way to do this then a alternative would be fine but it would need to work the same way as described however.
On request here is the runnable code for my timer.
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");
}
}
The
timer.schedulemethods that take 3 args repeat execution, so if run is true, the timer will start executing tasks.If you want to stop the timer, you can always call
timer.cancel, but you need to save a reference to the timer outside theEventmethod.Reading the
Timerjavadocs should help here http://docs.oracle.com/javase/6/docs/api/java/util/Timer.htmlEDIT: Here is an example of how this might work