I am trying to create a Timer / TimerTask that will work on the same day of every month. I cannot schedule a repeating timer, because a month will not always be the same length of time.
So here is my solution:
public class MyTask extends TimerTask {
public void run(){
if(scheduledExecutionTime() != 0){
TimerHelper.restartMyTimer();
}
}
}
public class TimerHelper {
public static HashTable timersTable = new HashTable();
public static void restartMyTimer(){
Calendar runDate = Calendar.getInstance();
runDate.set(Calendar.DAY_OF_MONTH, 1);
runDate.set(Calendar.HOUR_OF_DAY, 4);
runDate.set(Calendar.MINUTE, 0);
runDate.add(Calendar.MONTH, 1);
MyTask myTask = new MyTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, runDate.getTime());
timersTable = new HashTable();
timersTable.put("1", myTimer);
}
}
The problem, I think I am faced with the fact that since the first TimerTask creates a second timer, will the first timer be saved because it created the second? After the code ends the first timer, will this thread and object take care of garbage collection? Over time, I do not want to create a bunch of threads that do nothing but are not deleted. Perhaps I do not have a proper understanding of how streams and timers work ...
I am open to suggestions on other ways to create a monthly timer if I do not need to use third-party JARs.
Thank!