Sometimes it is very important to schedule tasks. Threading can be used in such cases. In following example, we schedules 3 tasks and the tasks were executed according to the given time interval.
import java.util.Timer;
import java.util.TimerTask;
public class Reminder {
Timer timer;
public Reminder(int seconds, String task) {
timer = new Timer();
timer.schedule(new RemindTask(task), seconds * 1000);
}
class RemindTask extends TimerTask {
String task;
RemindTask(String task){
this.task = task;
}
public void run() {
System.out.println("Task: " + task + " executed");
timer.cancel();
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new Reminder(2, "Task1");
new Reminder(5, "Task2");
new Reminder(3, "Task3");
System.out.println("Tasks scheduled.");
}
}