• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: How to run Timer independently in Java?

Resolved: How to run Timer independently in Java?

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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 new instance but still cannot solve the issue. How can I make sure the timers are ran independently?
Code:
To Trigger the timer:
The value object class:
Output:
In short, seems the variables in former Timer are being overwritten by the later Timer.

Answer:

As commented, your main problem seems to be making your variable timerVO 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!

java multithreading timer timertask
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Use Svelte Component as Slot

26/03/2023

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Resolved: How to separate multiple answers in one column, for multiple columns, by creating extra columns

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.