I need to execute an action after a certain time has passed only once. I have tried with the following:
Timeline contador = new Timeline(new KeyFrame(
Duration.seconds(4),
acción -> System.out.println("acción acontecida")));
contador.play();
}
It seems to work fine but, I want to know if it is the best way or is there another more recommended way.
To execute tasks repetitively, there are several alternatives:
A first and very simple approach to implement is to use
Timer
andTimerTask
, both from the java.util package:There are some very important considerations to keep in mind when working with this approach: an exception thrown in TimerTask terminates the Timer thread, with no possibility of being able to restart it, so you have to do exception handling. If we launch the task with
schedule
and it takes more than the stipulated time (let's say it takes 3 seconds more than the 2 seconds established) the next task will not be executed until the following 3+2 seconds. WithscheduleAtFixedRate
the opposite occurs; instead of executing at 3+2 sec it will run at 1 sec to try to adjust (the previous task consumed the 2 sec plus 1 sec of the new task). Depending on your requirements you must configure it in one way or another.Another approach is to use
ScheduledExecutorService
an implementation ofExecutorService
:ScheduledExecutorService allows you to schedule tasks to run periodically and/or with a delayed start just like Timer but it is much more flexible and unlike Timer it will not stop if an exception is generated in any of the tasks it handles.
The following post will guide you more about the main differences and benefits between Timer and ExecutorService: https://stackoverflow.com/questions/409932/java-timer-vs-executorservice
Lastly,
Timeline
it is more specific purpose and geared towards animation in JavaFX. I recommend that you use one of the two approaches above.