Question:I am trying to build multiple
timersand scheduled independent tasks for each of them. I have a
constructorfor holding a
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 new instance but still cannot solve the issue. How can I make sure the timers are ran independently?
Timerare being overwritten by the later
Answer:As commented, your main problem seems to be making your variable
statickeyword means you want only one such value rather than each instance having its own value known by that name. In other words,
staticis not object-oriented.
So each time you execute
timerVO = obj;, you replace the previously stored value with the current one. You have only a single
timerVOin your entire app, because you marked it
timerVOcan contain only a single value, the value last assigned.
I already initiate each timer as new instance but still cannot solve the issue.
But… all those timer objects you instantiated share the same single
Minor issue: Class names start with an uppercase letter. So
public class varObjectvoshould be
public class VarObjectvo.
Another minor issue: Naming a method “…Constructor” is confusing. That word has a very specific crucial meaning in Java. A constructor in Java is always named the same as the class name.
Bigger picture: You are not taking advantage of modern Java. If you read carefully the Javadoc of
TimerTaskclasses, you’ll see they were supplanted years ago by the Executors framework.
To use executors, define your tasks as implementing either
Callable. Then establish a
ScheduledExecutorService. Submit instances of your tasks to that service for repeated execution.
Search Stack Overflow to learn more. Scheduled executor service has been covered many many times already.
Some rough untested code follows.
If you have better answer, please add a comment about this, thank you!