import java.lang.*; import java.util.*; class MyTimerTask extends TimerTask { private int MAX_TARDINESS = 15; private String myName = null; public MyTimerTask(String aName) {myName=aName;} public void run() { // This is the main body of the thread System.err.println("\tTimerTask"+myName+": Started"); if (System.currentTimeMillis() - scheduledExecutionTime() >= MAX_TARDINESS) return; // Too late; skip this execution. // Perform the task System.err.println("\t\tTimerTask"+myName+": running @ " + System.currentTimeMillis()); return; } } class Initialise { public static void main(String[] argv) { Thread.currentThread().setName("main:"); MyTimerTask aTimerTask = new MyTimerTask(" one "); MyTimerTask bTimerTask = new MyTimerTask(" two "); Timer aTimer = new Timer(false); // Not a daemon timer // Start it after 10 milliseconds, with a period of 30 milliseconds aTimer.scheduleAtFixedRate(aTimerTask, 10L, 20L); // Start it after 30 milliseconds, with a period of 30 milliseconds aTimer.scheduleAtFixedRate(bTimerTask, 30L, 30L); try { Thread.currentThread().sleep(100L); } catch (InterruptedException ie) { } bTimerTask.cancel(); // The following is wrong - we cannot re-schedule a canceled task. // aTimer.scheduleAtFixedRate(bTimerTask, 30L, 30L); try { Thread.currentThread().sleep(100L); } catch (InterruptedException ie) { } // Cancel all timer tasks aTimer.cancel(); return; } }