Java/Development Class/Timer

Материал из Java эксперт
Перейти к: навигация, поиск

A simple implementation of the Java 1.3 java.util.Timer API

   <source lang="java">
  

/*

* Copyright (c) 2004 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book, 
* please visit http://www.davidflanagan.ru/javaexamples3.
*/

import java.util.ruparator; import java.util.Date; import java.util.SortedSet; import java.util.TreeSet; abstract class TimerTask implements Runnable {

 boolean cancelled = false; // Has it been cancelled?
 long nextTime = -1; // When is it next scheduled?
 long period; // What is the execution interval
 boolean fixedRate; // Fixed-rate execution?
 protected TimerTask() {
 }
 /**
  * Cancel the execution of the task. Return true if it was actually running,
  * or false if it was already cancelled or never scheduled.
  */
 public boolean cancel() {
   if (cancelled)
     return false; // Already cancelled;
   cancelled = true; // Cancel it
   if (nextTime == -1)
     return false; // Never scheduled;
   return true;
 }
 /**
  * When it the timer scheduled to execute? The run() method can use this to
  * see whether it was invoked when it was supposed to be
  */
 public long scheduledExecutionTime() {
   return nextTime;
 }
 /**
  * Subclasses must override this to provide that code that is to be run. The
  * Timer class will invoke this from its internal thread.
  */
 public abstract void run();
 // This method is used by Timer to tell the Task how it is scheduled.
 void schedule(long nextTime, long period, boolean fixedRate) {
   this.nextTime = nextTime;
   this.period = period;
   this.fixedRate = fixedRate;
 }
 // This will be called by Timer after Timer calls the run method.
 boolean reschedule() {
   if (period == 0 || cancelled)
     return false; // Don"t run it again
   if (fixedRate)
     nextTime += period;
   else
     nextTime = System.currentTimeMillis() + period;
   return true;
 }

} /**

* This class is a simple implementation of the Java 1.3 java.util.Timer API
*/

public class Timer {

 // This sorted set stores the tasks that this Timer is responsible for.
 // It uses a comparator to sort the tasks by scheduled execution time.
 SortedSet tasks = new TreeSet(new Comparator() {
   public int compare(Object a, Object b) {
     return (int) (((TimerTask) a).nextTime - ((TimerTask) b).nextTime);
   }
   public boolean equals(Object o) {
     return this == o;
   }
 });
 // This is the thread the timer uses to execute the tasks.
 // The TimerThread class is defined below.
 TimerThread timer;
 /** This constructor create a Timer that does not use a daemon thread */
 public Timer() {
   this(false);
 }
 /** The main constructor: the internal thread is a daemon if specified */
 public Timer(boolean isDaemon) {
   timer = new TimerThread(isDaemon); // TimerThread is defined below
   timer.start(); // Start the thread running
 }
 /** Stop the timer thread, and discard all scheduled tasks */
 public void cancel() {
   synchronized (tasks) { // Only one thread at a time!
     timer.pleaseStop(); // Set a flag asking the thread to stop
     tasks.clear(); // Discard all tasks
     tasks.notify(); // Wake up the thread if it is in wait().
   }
 }
 /** Schedule a single execution after delay milliseconds */
 public void schedule(TimerTask task, long delay) {
   task.schedule(System.currentTimeMillis() + delay, 0, false);
   schedule(task);
 }
 /** Schedule a single execution at the specified time */
 public void schedule(TimerTask task, Date time) {
   task.schedule(time.getTime(), 0, false);
   schedule(task);
 }
 /** Schedule a periodic execution starting at the specified time */
 public void schedule(TimerTask task, Date firstTime, long period) {
   task.schedule(firstTime.getTime(), period, false);
   schedule(task);
 }
 /** Schedule a periodic execution starting after the specified delay */
 public void schedule(TimerTask task, long delay, long period) {
   task.schedule(System.currentTimeMillis() + delay, period, false);
   schedule(task);
 }
 /**
  * Schedule a periodic execution starting after the specified delay. Schedule
  * fixed-rate executions period ms after the start of the last. Instead of
  * fixed-interval executions measured from the end of the last.
  */
 public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
   task.schedule(System.currentTimeMillis() + delay, period, true);
   schedule(task);
 }
 /** Schedule a periodic execution starting after the specified time */
 public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
   task.schedule(firstTime.getTime(), period, true);
   schedule(task);
 }
 // This internal method adds a task to the sorted set of tasks
 void schedule(TimerTask task) {
   synchronized (tasks) { // Only one thread can modify tasks at a time!
     tasks.add(task); // Add the task to the sorted set of tasks
     tasks.notify(); // Wake up the thread if it is waiting
   }
 }
 /**
  * This inner class defines the thread that runs each of the tasks at their
  * scheduled times
  */
 class TimerThread extends Thread {
   // This flag is will be set true to tell the thread to stop running.
   // Note that it is declared volatile, which means that it may be
   // changed asynchronously by another thread, so threads must always
   // read its current value, and not used a cached version.
   volatile boolean stopped = false;
   // The constructor
   TimerThread(boolean isDaemon) {
     setDaemon(isDaemon);
   }
   // Ask the thread to stop by setting the flag above
   void pleaseStop() {
     stopped = true;
   }
   // This is the body of the thread
   public void run() {
     TimerTask readyToRun = null; // Is there a task to run right now?
     // The thread loops until the stopped flag is set to true.
     while (!stopped) {
       // If there is a task that is ready to run, then run it!
       if (readyToRun != null) {
         if (readyToRun.cancelled) { // If it was cancelled, skip.
           readyToRun = null;
           continue;
         }
         // Run the task.
         readyToRun.run();
         // Ask it to reschedule itself, and if it wants to run
         // again, then insert it back into the set of tasks.
         if (readyToRun.reschedule())
           schedule(readyToRun);
         // We"ve run it, so there is nothing to run now
         readyToRun = null;
         // Go back to top of the loop to see if we"ve been stopped
         continue;
       }
       // Now acquire a lock on the set of tasks
       synchronized (tasks) {
         long timeout; // how many ms "till the next execution?
         if (tasks.isEmpty()) { // If there aren"t any tasks
           timeout = 0; // Wait "till notified of a new task
         } else {
           // If there are scheduled tasks, then get the first one
           // Since the set is sorted, this is the next one.
           TimerTask t = (TimerTask) tasks.first();
           // How long "till it is next run?
           timeout = t.nextTime - System.currentTimeMillis();
           // Check whether it needs to run now
           if (timeout <= 0) {
             readyToRun = t; // Save it as ready to run
             tasks.remove(t); // Remove it from the set
             // Break out of the synchronized section before
             // we run the task
             continue;
           }
         }
         // If we get here, there is nothing ready to run now,
         // so wait for time to run out, or wait "till notify() is
         // called when something new is added to the set of tasks.
         try {
           tasks.wait(timeout);
         } catch (InterruptedException e) {
         }
         // When we wake up, go back up to the top of the while loop
       }
     }
   }
 }
 /** This inner class defines a test program */
 public static class Test {
   public static void main(String[] args) {
     final TimerTask t1 = new TimerTask() { // Task 1: print "boom"
       public void run() {
         System.out.println("boom");
       }
     };
     final TimerTask t2 = new TimerTask() { // Task 2: print "BOOM"
       public void run() {
         System.out.println("\tBOOM");
       }
     };
     final TimerTask t3 = new TimerTask() { // Task 3: cancel the tasks
       public void run() {
         t1.cancel();
         t2.cancel();
       }
     };
     // Create a timer, and schedule some tasks
     final Timer timer = new Timer();
     timer.schedule(t1, 0, 500); // boom every .5sec starting now
     timer.schedule(t2, 2000, 2000); // BOOM every 2s, starting in 2s
     timer.schedule(t3, 5000); // Stop them after 5 seconds
     // Schedule a final task: starting in 5 seconds, count
     // down from 5, then destroy the timer, which, since it is
     // the only remaining thread, will cause the program to exit.
     timer.scheduleAtFixedRate(new TimerTask() {
       public int times = 5;
       public void run() {
         System.out.println(times--);
         if (times == 0)
           timer.cancel();
       }
     }, 5000, 500);
   }
 }

}


 </source>
   
  
 
  



Class encapsulating timer functionality

   <source lang="java">
 

/*

* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
* 
* Project: OpenSubsystems
* 
* $Id: MyTimer.java,v 1.5 2007/01/07 06:14:00 bastafidli Exp $
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License. 
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
*/

/**

* Class encapsulating timer functionality.
* 
* @version $Id: MyTimer.java,v 1.5 2007/01/07 06:14:00 bastafidli Exp $
* @author Miro Halas
* @code.reviewer Miro Halas
* @code.reviewed Initial revision
*/

public class MyTimer {

  // Attributes ///////////////////////////////////////////////////////////////
  
  /**
   * Remeber start time here.
   */
  private long m_lStartTime;
  
  /**
   * Remeber stop time here.
   */
  private long m_lStopTime;
  // Constructors /////////////////////////////////////////////////////////////
  
  /**
   * Default constructor.
   * Starts counting fro the moment it is cosntructed.
   */
  public MyTimer(
  )
  {
     reset();
  }
  // Logic ////////////////////////////////////////////////////////////////////
  
  /**
   * @return long - start time;
   */
  public long getStartTime()
  {
     return m_lStartTime;
  }
  /**
   * @return - stop time;
   */
  public long getStopTime()
  {
     return m_lStopTime;
  }
  /**
   * Reset the counter and start counting from scratch.
   */
  public void reset(
  )
  {
     m_lStartTime = System.currentTimeMillis();
     m_lStopTime = 0;
  }
  /**
   * Stop the timer.
   */
  public void stop(
  )
  {
     m_lStopTime = System.currentTimeMillis();
  }
  /**
   * Get timer duration (the timer doesn"t stop) in milliseconds.
   * 
   * @return long - difference between stop and start time.
   */
  public long getDuration(
  )
  {
     long lStopTime;
     if (m_lStopTime == 0)
     {
        lStopTime = System.currentTimeMillis();
     }
     else
     {
        lStopTime = m_lStopTime;
     }
     return lStopTime - m_lStartTime;
  }
  /**
   * Print the state of the timer without stopping it.
   * @return String - timing information
   */
  public String toString(
  )
  {
     long lTotalMS   = getDuration();
     long lMS        = lTotalMS % 1000;
     long lTotalSecs = lTotalMS / 1000;
     long lSecs      = lTotalSecs % 60;
     long lTotalMins = lTotalSecs / 60;
     long lMinutes   = lTotalMins % 60;
     long lHours     = lTotalMins / 60;
     StringBuffer sbBuffer = new StringBuffer();
     if (lHours > 0)
     {
        sbBuffer.append(lHours);
        sbBuffer.append(":");
        sbBuffer.append(lMinutes);
        sbBuffer.append(":");
        sbBuffer.append(lSecs);
        sbBuffer.append(".");
        sbBuffer.append(lMS);
     }
     else if (lMinutes > 0)
     {
        sbBuffer.append(lMinutes);
        sbBuffer.append(":");
        sbBuffer.append(lSecs);
        sbBuffer.append(".");
        sbBuffer.append(lMS);
     }
     else if (lSecs > 0)
     {
        sbBuffer.append(lSecs);
        sbBuffer.append(".");
        sbBuffer.append(lMS);
        sbBuffer.append(" seconds");
     }
     else
     {
        sbBuffer.append(lMS);
        sbBuffer.append(" ms");
     }
     
     return sbBuffer.toString();
  }

}


 </source>
   
  
 
  



Create a scheduled task using timer

   <source lang="java">
  

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class Main extends TimerTask {

 private DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
 public static void main(String[] args) {
   TimerTask task = new Main();
   Timer timer = new Timer();
   timer.scheduleAtFixedRate(task, new Date(), 1000);
 }
 public void run() {
   System.out.println(formatter.format(new Date()));
 }

}


 </source>
   
  
 
  



Create a Timer object

   <source lang="java">
  

import java.util.Timer; import java.util.TimerTask; public class Main {

 Timer timer;
 public Main(int seconds) {
   timer = new Timer();
   timer.schedule(new ToDoTask(), seconds * 1000);
 }
 class ToDoTask extends TimerTask {
   public void run() {
     System.out.println("working");
     timer.cancel(); 
   }
 }
 public static void main(String args[]) {
   new Main(5);
 }

}


 </source>
   
  
 
  



extends TimerTask to create your own task

   <source lang="java">
  

import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.TimerTask; class MyTask extends TimerTask {

 private DataOutputStream out;
 public MyTask(OutputStream dest) {
   out = new DataOutputStream(dest);
 }
 public void run() {
   try {
     out.writeInt(1);
     out.writeUTF("asdf");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

}


 </source>
   
  
 
  



Pause and start a timer task

   <source lang="java">
  

import java.util.Timer; import java.util.TimerTask; class MyTask extends TimerTask {

 int counter;
 public MyTask() {
   counter = 0;
 }
 public void run() {
   counter++;
   System.out.println("Ring " + counter);
 }
 public int getCount() {
   return counter;
 }

} public class Main {

 private boolean running;
 private MyTask task;
 private Timer timer;
 public Main() {
   timer = new Timer(true);
 }
 public boolean isRinging() {
   return running;
 }
 public void startRinging() {
   running = true;
   task = new MyTask();
   timer.scheduleAtFixedRate(task, 0, 3000);
 }
 public void doIt() {
   running = false;
   System.out.println(task.getCount() + " times");
   task.cancel();
 }
 public static void main(String[] args) {
   Main phone = new Main();
   phone.startRinging();
   try {
     System.out.println("started running...");
     Thread.sleep(20000);
   } catch (InterruptedException e) {
   }
   phone.doIt();
 }

}


 </source>
   
  
 
  



Schedule a task by using Timer and TimerTask.

   <source lang="java">
  

import java.util.Date; import java.util.Timer; import java.util.TimerTask; class AutoTask extends TimerTask {

 AutoTask() {
 }
 public void run() {
   System.out.println(new Date());
 }

} public class Main {

 public static void main(String args[]) {
   AutoTask myTask = new AutoTask();
   Timer bkTimer = new Timer();
   bkTimer.schedule(myTask, 2000, 2000);
   for (int i = 0; i < 5; i++) {
     try {
       Thread.sleep(2100);
     } catch (InterruptedException exc) {
     }
   }
   bkTimer.cancel();
 }

}


 </source>
   
  
 
  



Scheduling a Timer Task to Run at a Certain Time

   <source lang="java">
  

import java.sql.Date; import java.util.Timer; import java.util.TimerTask; public class Main {

 public static void main(String[] argv) throws Exception {
 
   Date timeToRun = new Date(System.currentTimeMillis() + numberOfMillisecondsInTheFuture);
   Timer timer = new Timer();
   timer.schedule(new TimerTask() {
     public void run() {
       System.out.println("doing");
     }
   }, timeToRun);
 }

}


 </source>
   
  
 
  



Scheduling a Timer Task to Run Repeatedly

   <source lang="java">
  

import java.util.Timer; import java.util.TimerTask; public class Main {

 public static void main(String[] argv) throws Exception {
   int delay = 5000; // delay for 5 sec.
   int period = 1000; // repeat every sec.
   Timer timer = new Timer();
   timer.scheduleAtFixedRate(new TimerTask() {
     public void run() {
       System.out.println("doing"); 
     }
   }, delay, period);
 }

}


 </source>
   
  
 
  



Swing also provide a Timer class. A Timer object will send an ActionEvent to the registered ActionListener.

   <source lang="java">
  

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public class Main implements ActionListener {

 Timer t = new Timer(1000, this);
 Main() {
   t.start();
 }
 public void actionPerformed(ActionEvent e) {
   System.out.println("working");
 }
 public static void main(String args[]) {
   Main main = new Main();
 }

}


 </source>
   
  
 
  



Timeout Observer

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*/

import java.util.Enumeration; import java.util.Vector; /**

* Generalization of ExecuteWatchdog
* 
* @see org.apache.rumons.exec.ExecuteWatchdog
*/

public class Watchdog implements Runnable {

 private Vector observers = new Vector(1);
 private final long timeout;
 private boolean stopped = false;
 public Watchdog(final long timeout) {
   if (timeout < 1) {
     throw new IllegalArgumentException("timeout must not be less than 1.");
   }
   this.timeout = timeout;
 }
 public void addTimeoutObserver(final TimeoutObserver to) {
   observers.addElement(to);
 }
 public void removeTimeoutObserver(final TimeoutObserver to) {
   observers.removeElement(to);
 }
 protected final void fireTimeoutOccured() {
   Enumeration e = observers.elements();
   while (e.hasMoreElements()) {
     ((TimeoutObserver) e.nextElement()).timeoutOccured(this);
   }
 }
 public synchronized void start() {
   stopped = false;
   Thread t = new Thread(this, "WATCHDOG");
   t.setDaemon(true);
   t.start();
 }
 public synchronized void stop() {
   stopped = true;
   notifyAll();
 }
 public synchronized void run() {
   final long until = System.currentTimeMillis() + timeout;
   long now;
   while (!stopped && until > (now = System.currentTimeMillis())) {
     try {
       wait(until - now);
     } catch (InterruptedException e) {
     }
   }
   if (!stopped) {
     fireTimeoutOccured();
   }
 }

} /**

* Interface for classes that want to be notified by Watchdog.
* 
* @see org.apache.rumons.exec.Watchdog
*/

interface TimeoutObserver {

 /**
  * Called when the watchdow times out.
  * 
  * @param w
  *          the watchdog that timed out.
  */
 void timeoutOccured(Watchdog w);

}

 </source>
   
  
 
  



Timer and TimerTask Classes

   <source lang="java">
  

import java.util.Timer; import java.util.TimerTask; class GCTask extends TimerTask {

 public void run() {
   System.out.println("Running the scheduled task...");
   System.gc();
 }

} public class Main {

 public static void main(String[] args) {
   Timer timer = new Timer();
   GCTask task = new GCTask();
   timer.schedule(task, 5000, 5000);
   int counter = 1;
   while (true) {
     try {
       Thread.sleep(500);
     } catch (InterruptedException e) {
     }
   }
 }

}


 </source>
   
  
 
  



Timer Schedule a task that executes once every second

   <source lang="java">
  

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Toolkit; import java.util.Timer; import java.util.TimerTask; /**

* Schedule a task that executes once every second.
*/

public class AnnoyingBeep {

 Toolkit toolkit;
 Timer timer;
 public AnnoyingBeep() {
   toolkit = Toolkit.getDefaultToolkit();
   timer = new Timer();
   timer.schedule(new RemindTask(), 0, //initial delay
       1 * 1000); //subsequent rate
 }
 class RemindTask extends TimerTask {
   int numWarningBeeps = 3;
   public void run() {
     if (numWarningBeeps > 0) {
       toolkit.beep();
       System.out.println("Beep!");
       numWarningBeeps--;
     } else {
       toolkit.beep();
       System.out.println("Time"s up!");
       //timer.cancel(); //Not necessary because we call System.exit
       System.exit(0); //Stops the AWT thread (and everything else)
     }
   }
 }
 public static void main(String args[]) {
   System.out.println("About to schedule task.");
   new AnnoyingBeep();
   System.out.println("Task scheduled.");
 }

}



 </source>
   
  
 
  



Timer Skipping Beep

   <source lang="java">
  

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Toolkit; import java.util.Timer; import java.util.TimerTask; /**

* Schedule a task that executes once every second.
*/

public class SkippingBeep {

 Toolkit toolkit;
 Timer timer;
 public SkippingBeep() {
   toolkit = Toolkit.getDefaultToolkit();
   timer = new Timer();
   timer.scheduleAtFixedRate(new RemindTask(), 0, //initial delay
       1 * 1000); //subsequent rate
 }
 class RemindTask extends TimerTask {
   int numWarningBeeps = 3;
   public void run() {
     if (numWarningBeeps-- > 0) {
       long time = System.currentTimeMillis();
       if (time - scheduledExecutionTime() > 5) {
         return;
       }
       //If it"s not too late, beep.
       toolkit.beep();
       System.out.println("Beep!");
     } else {
       toolkit.beep();
       System.out.println("Time"s up!");
       //timer.cancel(); //Not necessary because we call System.exit
       System.exit(0); //Stops the AWT thread (and everything else)
     }
   }
 }
 public static void main(String args[]) {
   System.out.println("About to schedule task.");
   new SkippingBeep();
   System.out.println("Task scheduled.");
 }

}



 </source>
   
  
 
  



Timer utilities

   <source lang="java">
  
import java.util.Timer;

import java.util.TimerTask; /*

* UtilTimerDemo.java
*
* Created on May 2, 2007, 3:13 PM
*
* Copyright (c) 2007, Sun Microsystems, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the TimingFramework project nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**

*
* @author Chet
*/

public class UtilTimerDemo extends TimerTask {

   private static long prevTime = 0;
   private static long startTime = 0;
   private static final long DELAY = 100;
   private static final long DURATION = 5 * DELAY;
   private static final long PROCESSING_TIME = 30;
   private static final long INITIAL_PROCESSING_TIME = 2 * DELAY;
   private static Timer timer = null;
   private boolean firstTime = true;
   private static boolean runningFixedRate = false;
   
   /** 
    * This method will be called during every tick of the Timers.
    * We insert an artificial delay each time, to simulate some processing.
    * The first time through, this delay is greater than the delay between
    * timing events, so that we can see how this hiccup is handled by
    * fixed-rate and fixed-delay timers.
    */
   public void run() {
       long nowTime = System.currentTimeMillis();
       long elapsedTime = nowTime - prevTime;
       long totalTime = nowTime - startTime;
       System.out.println("Elapsed time = " + elapsedTime);
       if (totalTime > DURATION) {
           timer.cancel();
       }
       prevTime = nowTime;
       try {
           if (firstTime) {
               Thread.sleep(INITIAL_PROCESSING_TIME);
               firstTime = false;
           } else {
               Thread.sleep(PROCESSING_TIME);
           }
       } catch (Exception e) {}
   }
   
   public UtilTimerDemo() {
       firstTime = true;
   }
   
   public static void main(String[] args) {
       // Start and run a fixed-delay timer
       timer = new Timer();
       startTime = prevTime = System.currentTimeMillis();
       System.out.println("Fixed Delay Times");
       timer.schedule(new UtilTimerDemo(), DELAY, DELAY);
       // Sleep long enough to let the first timer finish
       try {
           Thread.sleep(DURATION*2);
       } catch (Exception e) {}
       
       // Start and run a fixed-rate timer
       timer = new Timer();
       startTime = prevTime = System.currentTimeMillis();
       System.out.println("Fixed Rate Times");
       timer.scheduleAtFixedRate(new UtilTimerDemo(), DELAY, DELAY);
   }

}



 </source>
   
  
 
  



Use java.util.Timer to schedule a task to execute once 5 seconds have passed

   <source lang="java">
  

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.Toolkit; import java.util.Timer; import java.util.TimerTask; /**

* Simple demo that uses java.util.Timer to schedule a task to execute once 5
* seconds have passed.
*/

public class ReminderBeep {

 Toolkit toolkit;
 Timer timer;
 public ReminderBeep(int seconds) {
   toolkit = Toolkit.getDefaultToolkit();
   timer = new Timer();
   timer.schedule(new RemindTask(), seconds * 1000);
 }
 class RemindTask extends TimerTask {
   public void run() {
     System.out.println("Time"s up!");
     toolkit.beep();
     //timer.cancel(); //Not necessary because we call System.exit
     System.exit(0); //Stops the AWT thread (and everything else)
   }
 }
 public static void main(String args[]) {
   System.out.println("About to schedule task.");
   new ReminderBeep(5);
   System.out.println("Task scheduled.");
 }

}



 </source>