Question:
I am trying to build multipletimers
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 new instance but still cannot solve the issue. How can I make sure the timers are ran independently?Code:
Timer
are being overwritten by the later Timer
.Answer:
As commented, your main problem seems to be making your variabletimerVO
static
.The
static
keyword means you want only one such value rather than each instance having its own value known by that name. In other words, static
is 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 timerVO
in your entire app, because you marked it static
. That timerVO
can contain only a single value, the value last assigned.You said:
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
static
timerVO
object.Minor issue: Class names start with an uppercase letter. So
public class varObjectvo
should 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
Timer
and TimerTask
classes, you’ll see they were supplanted years ago by the Executors framework.To use executors, define your tasks as implementing either
Runnable
or 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!