Getting start with Java scheduling

Kavindu Gayan
2 min readDec 1, 2020

--

In java scheduling, Basically there are two classes involving. They are,

Timer Class

TimerTask Class

Timer Class

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

This class scales to large numbers of concurrently scheduled tasks (thousands should present no problem). Internally, it uses a binary heap to represent its task queue, so the cost to schedule a task is O(log n), where n is the number of concurrently scheduled tasks.

class methods

cancel() — Terminates this timer, discarding any currently scheduled tasks.

purge() — Removes all cancelled tasks from this timer’s task queue.

schedule(TimerTask task, Date time) — Schedules the specified task for execution at the specified time.

schedule(TimerTask task, Date firstTime, long period) — Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

schedule(TimerTask task, long delay) — Schedules the specified task for execution after the specified delay.

schedule(TimerTask task, long delay, long period) — Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.

scheduleAtFixedRate(TimerTask task, Date firstTime, long period) — Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

scheduleAtFixedRate(TimerTask task, long delay, long period) — Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.

TimerTask Class

A task that can be scheduled for one-time or repeated execution by a Timer. TimerTask is an abstract class which implements Runnable interface. So once applcation loads the TimerTask class it invokes the run() method.

Sample source code:

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

public class JavaScheduler {
public static void main(String[] args) {
/*A facility for threads to schedule tasks for future execution in a
background thread. Tasks may be scheduled for one-time execution, or for
repeated execution at regular intervals.*/
Timer timer= new Timer();
/*A task that can be scheduled for one-time or repeated execution by a Timer.*/
TimerTask timerTask= new TimerTask() {
int count=0;
@Override
public void run() {
if (count!=10) {
System.out.println("running the task "+count);
count++;
}
else {
timer.cancel();//Terminates this timer, discarding any currently scheduled tasks
timer.purge();//Removes all cancelled tasks from this timer's task queue.
System.out.println("cancel and purge the task");
}
}
};
timer.schedule(timerTask,2000,1000);//scheduler starts with 2 seconds delay and runs at every seconds.
}
}

--

--

No responses yet