Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is Java Timer Class? How to schedule a task to run after specific interval?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2014/02/17
Muhammad Khatree
by Muhammad Khatree , Associate Director – Technology Advisory , KPMG Australia

The Timer class is used to perform an action after a time delay. Here is an example:

 

import java.util.Timer;

import java.util.TimerTask;

 

public class TimerExample{

    Timer test_timer;

 

    public TimeDelay(int seconds) {

        test_timer = new Timer();

        test_timer.schedule(new DelayTask(), seconds*1000);

}

 

    class DelayTask extends TimerTask {

        public void run() {

            System.out.format("Timer has run out.%n");

            test_timer.cancel(); 

        }

    }

 

    public static void main(String args[]) {

        new TimeDelay(5);

        System.out.format("Task has been scheduled.%n");

    }

}

 

More Questions Like This