Java-Timer and TimerTask

Timer and TimerTask

Timer and TimerTask use to you can create a thread that runs in the background, waiting for a specific time. When the time arrives, the task linked to that thread is executed. Various options allow you to schedule a task for repeated execution, and to schedule a task to run on a specific date. Although it was always possible to manually create a task that would be executed at a specific time using the Thread class, Timer and TimerTask greatly simplify this process.

Timer and TimerTask work together. Timer is the class that you will use to schedule a task for execution. The task being scheduled must be an instance of TimerTask. Thus, to schedule a task, you will first create a TimerTask object and then schedule it for execution using an instance of Timer. TimerTask implements the Runnable interface; thus, it can be used to create a thread of execution.

TimerTask define the method run( ) is abstract, which means that it must be overridden. The run( ) method, defined by the Runnable interface, contains the code that will be executed. Thus, the easiest way to create a timer task is to extend TimerTask and override run( ). Once a task has been created, it is scheduled for execution by an object of type Timer. The constructor for Timer are :

Timer( );

Once a Timer has been created, you will schedule a task by calling schedule( ) on the Timer that you created.

void schedule(TimerTask Task, long wait, long repeat);

Task is scheduled for execution after the period passed in wait has elapsed. The task is then executed repeatedly at the interval specified by repeat. Both wait and repeat are specified in milliseconds. The cancel( ) method is used to end the task.

Program

retretertertertret

Program Source

import java.util.Timer;
import java.util.TimerTask;

class TimerT extends TimerTask {
    
    int count = 0;
    
    public void run()
    {
        System.out.println("count = "+count);
        count++;
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        TimerT task = new TimerT();
        Timer time = new Timer();
        time.schedule(task,2000,500);
        
        while(true)
        {
            if(task.count == 10)
            {
                time.cancel();
                break;
            }
        }
    }
}

Leave a Comment