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. And I would time to set different lifespan for each timer, for example one timer will be terminated after 1 day whilst keep other run forever. I have a thought to build another a timer on top of those timers and control their status but I am afraid that the program would be messy and bulky. Is there any other method for this? Thanks
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.setLifespan('24'); //24 hour
timerVariable.setAliveTime(30); // seconds
tmpTimer.start(timerVariable); //timerVariable is a value object
}
}
}
The Constructor of timer:
import java.time.LocalDateTime;
import java.util.concurrent.*;
import java.util.Date;
public class TimerConstructor{
private static varObjectvo timerVO = null;
public void start(varObjectvo obj) {
timerVO = obj;
executor = Executors.newSingleThreadScheduledExecutor();
startTime = LocalDateTime.now();
endTime = startTime.plusSeconds(obj.getAliveTime());
timer.scheduleAtFixedRate(task, new Date(), 10000);
while (true) {
if (endTime.getHour()==LocalDateTime.now().getHour() &&
endTime.getMinute()==LocalDateTime.now().getMinute() &&
endTime.getSecond()==LocalDateTime.now().getSecond()) {
scheduleFuture.cancel(true);
executor.shutdown();
System.out.println("Cancelling " + scheduleFuture.toString());
break;
}
}
}
private class TimerChecker extends TimerTask {
public void run() {
System.out.println("It is timer " + timerVO.getIndex());
}
}
}
The value object class:
public class varObjectvo{
private Integer index;
private Integer lifespan;
public void setIndex(Integer i){
this.index = i;
}
public Integer getIndex(){
return this.index;
}
public void setLifespan(Integer i){
this.lifespan= i;
};
public Integer getLifespan(){
return this.lifespan;
};
}