Adding a timer to my program (javafx)

Timer is used to schedule tasks.. So where do you write those tasks?? Well you have to write those tasks in a TimerTask class…

Confused ? Let me break it down,

Timer timer = new Timer();

Now you have created a object of Timer class .. Now you have to do some task right? So to do that create an object of TimerTask.

TimerTask task = new TimerTask()
{
        public void run()
        {
            //The task you want to do       
        }

};

Now you have created a task where you should be defining the tasks you want to do inside the run method..

Why have I written a TimerTask class itself?? Thats because TimerTask is a abstract class with three methods.. So you need to define whichever method you want to use..

Now scheduling the task

timer.schedule(task,5000l);

Note the ‘l’ after 5000. It is to denote long data type because the schedule method is defined as

void schedule(TimerTask task,long milliseconds)

For further reference

https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

https://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

Leave a Comment