I need to run a function every 10 seconds in my java project. I want it to be like an infinite loop yet without using while(true) or thread.sleep...
Any ideas?
I need to run a function every 10 seconds in my java project. I want it to be like an infinite loop yet without using while(true) or thread.sleep...
Any ideas?
You can use a Timer with the method:
Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
Here, task
is the task you want to execute (derived from TimerTask
), period
is time in milliseconds between the execution of two tasks and delay
is the delay in milliseconds before each execution.
This is more or less a duplicate of Making a Thread to Sleep for 30 minutes. That question mentions the ScheduledExecutorService
, which I've used and been very happy with. It's a bit heavyweight, so Timer may be all that you need. The Java Tutorial has a decent example of how to use that.