Friday, September 3, 2010

Task scheduling in java – recurring tasks and one time occurring tasks

In this blog we will learn how to schedule a timer task to run at certain time. Java provides a facility to schedule tasks as per requirement.
java.util.TimerTask instance provides a task that can be scheduled to run one time or after scheduled periodic time. We can define actions to be performed by this timer task instance. We all need to override the run method of TimerTask class.
java.util.Timer Class provides the facility to schedule a timer task to occur in future in a separate background thread. Timer.schedule() method provides the functions to performed a task for one time or a periodic time interval. You can specify the initial delay.

Examples:
Scheduling a onetime occurring and a recurring task
MyTask.java

import java.util.Timer;
import java.util.TimerTask;
public class MyTask extends TimerTask {

// override the run method to perform a scheduled task action.
public void run() {
System.out.println("Running a task.");
}
}

MyTaskScheduler.java

import java.util.*;
public class MyTaskScheduler {
public static void main(String[] args) {
MyTask task = new MyTask();
Timer timer = new Timer();
// one time occurring task with specified 2 second initial delay and after every 1 second period.
timer.schedule (task, 2000, 1000);
// Schedule a task to run after every 1 second (1000 millisecond) – recurring task
timer.schedule( task, 1000);
}
}

We can also use Timer class’ method scheduleAtFixedRate() for recurring task.

This entry was originally published at Experts Support Blog

No comments:

Post a Comment