Skip to content
Advertisement

TimerTask class has to run only once in java

I have a class that runs for every 10 secs, but when I execute it more than once, multiple timers are started. If one timer is already running, I want the other timer calls to be ignored. I want only one timer to be running at a given point of time. Please help.

My code:

JavaScript

Advertisement

Answer

I want the 1st timer to be running always. Other timers calls should not be triggered at all.

Try with Singleton patten that allows only single instance of the class.

Sample code:

JavaScript

Now if you try to start another Task on the same instance it will result in below exception:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement