Menu
Topics Index
...
`

Simple Timer Task Example - Java Example Program


Simple Timer Task Example
import java.util.*;

class SimpleTimerTaskDemo
{
    public static void main(String arg[])
    {
        Timer timer = new Timer();
        MyPrintingTask printingTask = new MyPrintingTask();
        
        int delay = 3000; // THREE SECONDS
        System.out.println("Time Before scheduling : " + new Date());
        timer.schedule(printingTask, delay); // LINE A
        System.out.println("Time After scheduling : " + new Date());
        
        // SLEEP FOR SIX SECONDS, SO THAT THE SCHEDULED TASK IS COMPLETED
        try { Thread.sleep(6000); } catch(Exception e) {}; // LINE B
        timer.cancel();    
    }
}

class MyPrintingTask extends TimerTask
{
    public void run()
    {
        System.out.println("Task executed at : " + new Date());
    }
}
OUTPUT

Time Before scheduling : Sun Dec 28 01:46:44 EST 2014
Time After scheduling : Sun Dec 28 01:46:44 EST 2014
Task executed at : Sun Dec 28 01:46:47 EST 2014

DESCRIPTION

Here we created a custom task called MyPrintingTask which simply prints a line when it is executed. In the main method, we created a Timer and scheduled this printing task with a delay of 3 seconds. Which means, the task will be executed after 3 seconds. If you carefully observe the output, the first two lines are printed in 44th second, where as the task is executed in 47th second.
In normal world we do not need a sleep of 6 seconds in the main method, because we might be performing some other time taking task. We have used this sleep of 6 seconds only to demonstrate how Timer and TimerTask works.

NOTE: The output when you execute will differ since the time would have changed. Only observe the first two lines are printed once, where as the last line is executed after three seconds.

THINGS TO TRY
  • Change the delay from 3 seconds to 5 seconds and see if the output seconds change accordingly.
  • Remove LINE B and observe that the task is not executed, since the main method is complete and timer is cancelled, even before the task is triggered.
  • TRY THIS LOCALLY AFTER DOWNLOADING. Do not call the cancel method on the Timer and see that the program does not return and runs for ever.

© meritcampus 2019

All Rights Reserved.

Open In App