Sunday, December 28, 2014

Scheduling Task using Timer in Java

Java provides class called Timer using which you can schedule task at specific intervals.

Signature of Schedule method of Timer class follows as 
schedule(TimerTask task, Date firstTime, long period)

Here, task is the task to be executed
firstTime is firstTime at which task to be executed first
period is interval time in milliseconds at which task will be executed automatically at this interval.

Refer to Timer API Documentation.

Java Program to Schedule Task using Timer
package com.anuj.threading;

import java.text.ParseException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

 * @author Anuj
public class ScheduleTaskExample {

    public static void main(String[] args) throws ParseException {
        Date date = new Date(); //First time at which task is to be executed
        MyTimeTask task = new MyTimeTask();
        Timer timer = new Timer();

        int period = 15000;//15 seconds
        timer.schedule(task, date, period);

class MyTimeTask extends TimerTask {

    public void run() {
        System.out.println("Running Task: " + new Date());

Output :
Running Task: Sun Dec 28 14:55:08 IST 2014
Running Task: Sun Dec 28 14:55:23 IST 2014
Running Task: Sun Dec 28 14:55:38 IST 2014
Running Task: Sun Dec 28 14:55:53 IST 2014