Skip to content

Instantly share code, notes, and snippets.

@seyedsahil
Created September 4, 2019 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seyedsahil/7bb94c27bffb6918d5dc31a78cff79cd to your computer and use it in GitHub Desktop.
Save seyedsahil/7bb94c27bffb6918d5dc31a78cff79cd to your computer and use it in GitHub Desktop.
package org.sydlabz.taskgroup;
import java.util.Timer;
import java.util.TimerTask;
/**
* Tutorial demo program for Timer and TimerTask
* @author Seyed Sahil
*/
public class TaskGroup {
private Timer timer;
public TaskGroup(Timer timer) {
this.timer = timer;
// Schedule a series of tasks with different delay.
this.timer.schedule(new SimpleTask("A"), 1000);
this.timer.schedule(new SimpleTask("B"), 5000);
this.timer.schedule(new SimpleTask("C"), 3000);
this.timer.schedule(new SimpleTask("D"), 1500);
this.timer.schedule(new SimpleTask("E"), 10000);
this.timer.schedule(new SimpleTask("F"), 2000);
this.timer.schedule(new SimpleTask("G"), 6000);
this.timer.schedule(new SimpleTask("H"), 3000);
this.timer.schedule(new SimpleTask("I"), 100);
this.timer.schedule(new SimpleTask("J"), 8000);
}
private class SimpleTask extends TimerTask {
private String id;
public SimpleTask(String id) {
this.id = id;
}
@Override
public void run() {
System.out.println("Task " + this.id + " has been completed.");
}
}
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer();
new TaskGroup(timer);
// Wait for all the tasks to finish.
Thread.sleep(15000);
timer.cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment