I am trying to build multiple Timers
and scheduled independent tasks for each of them. I have a constructor for holding a Timer
and its variable. Then, I will call them one by one but I found that the variables, passed to the Timer
constructor, are overrode by each other. I already initiate each Timer
as a new instance but still cannot solve the issue. How can I make sure the timers are run independently?
Code:
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
TimerTrigger.INSTANCE.runTimer();
}
}
To Trigger the timer:
public enum TimerTrigger {
INSTANCE;
private TimerTrigger(){}
public void runTimer(){
for (int i = 0; i < 3; i++) {
System.out.println( "Initiaizing Timer " + i );
TimerConstructor tmpTimer = new TimerConstructor();
varObjectvo timerVariable = new varObjectvo();
timerVariable.setIndex(i);
// timerList.add(tmpTimer);
tmpTimer.start(timerVariable); //timerVariable is a value object
}
}
}
The Constructor of timer:
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
public class TimerConstructor{
private static varObjectvo timerVO = null;
Timer timer = null;
public void start(varObjectvo obj) {
timer = new Timer("Timer_" + obj.getIndex()); // will be Timer_1/2/3
timerVO = obj;
TimerChecker task = new TimerChecker();
timer.scheduleAtFixedRate(task, new Date(), 10000);
}
private class TimerChecker extends TimerTask {
public void run() {
System.out.println("It is timer " + timerVO.getIndex() + " from: " + timer.toString());
}
}
}
The value object class:
public class varObjectvo{
private Integer index;
public void setIndex(Integer i){
this.index = i;
};
public Integer getIndex(){
return this.index;
};
}
Output:
Hello World!
Initiaizing Timer 0
Initiaizing Timer 1
It is timer 0 from:java.util.Timer@6b45c377
It is timer 1 from:java.util.Timer@17481b7c
Initiaizing Timer 2
It is timer 2 from:java.util.Timer@48e94d09
It is timer 2 from:java.util.Timer@17481b7c
It is timer 2 from:java.util.Timer@48e94d09
It is timer 2 from:java.util.Timer@6b45c377
In short, seems the variables in former Timer
are being overwritten by the later Timer
.