import java.util.Timer; import java.util.TimerTask; import java.util.Calendar; import java.util.GregorianCalendar; // Unlike Swing Timers, general-purpose Timers each use their // own, separate, independent thread public class TimersThreadsTimerTask { Timer timer1 = new Timer(); Timer timer2 = new Timer(); Timer timer3 = new Timer(); public static void main(String[] args) { new TimersThreadsTimerTask(); } // Constructor: Start three Timers (threads) running simultaneously public TimersThreadsTimerTask() { // Alternate method: Set a 'Date' object to today at 10:42:00 p.m. /* Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 22); calendar.set(Calendar.MINUTE, 42); calendar.set(Calendar.SECOND, 0); Date dayTime = calendar.getTime(); timer1.schedule(new Task1(), dayTime); */ // Set a 'Calendar' object to today at 10:42:00 p.m. Calendar dayTime = new GregorianCalendar(new GregorianCalendar().get(Calendar.YEAR), new GregorianCalendar().get(Calendar.MONTH), new GregorianCalendar().get(Calendar.DATE), 22, 42); // Set the first Timer to run once at (or after) a specific date/time timer1.schedule(new Task1(), dayTime.getTime()); // Wait for five seconds, and then run the second Timer once timer2.schedule(new Task2(), 5000); // Start the third Timer immediately, and then run it every two seconds timer3.schedule(new Task3(), 0, 2000); } public class Task1 extends TimerTask { public void run() { for (int counter = 1; counter <= 5; counter++) System.out.println("Task #1: " + (counter)); } } public class Task2 extends TimerTask { public void run() { for (int counter = 1; counter <= 5; counter++) System.out.println("Task #2: " + (counter)); } } public class Task3 extends TimerTask { int counter = 1; public void run() { System.out.println("Task #3: " + (counter)); // Stop this Timer after it has run five times if (counter++ == 5) timer3.cancel(); } } }