A class to wait until a condition becomes true. : Timer « Development Class « Java






A class to wait until a condition becomes true.

        
/*
Copyright 2011 Karl-Michael Schneider

Licensed 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.
*/
//package org.jwatter.util;

/**
 * A class to wait until a condition becomes true. Periodically calls {@link #until()} and sleeps
 * for a specified amount of time if it returns false. If {@link #until()} does not return true
 * within the timeout, throws a {@link TimedOut} exception. If the timeout is 0, it may wait
 * forever, and a {@link TimedOut} exception is never thrown.
 * 
 * A concrete subclass must implement {@link #until()}.
 */
public abstract class Waiting {

    public static final int DEFAULT_TIMEOUT = 0;
    public static final int DEFAULT_SLEEP = 1000;
    public static final String DEFAULT_TIMEOUT_MESSAGE = "wait timed out";

    protected int timeout;
    protected int sleep;
    protected String timeoutMessage;

    /**
     * Creates and instance with the default settings.
     */
    public Waiting () {
        this(DEFAULT_TIMEOUT, DEFAULT_SLEEP, DEFAULT_TIMEOUT_MESSAGE);
    }

    /**
     * Creates an instance with the specified timeout message.
     * 
     * @param timeoutMessage
     *        the message in the {@link TimedOut} exception
     */
    public Waiting (String timeoutMessage) {
        this(DEFAULT_TIMEOUT, DEFAULT_SLEEP, timeoutMessage);
    }

    /**
     * Creates an instance that waits at most the specified time.
     * 
     * @param timeout
     *        the timeout in milliseconds.
     */
    public Waiting (int timeout) {
        this(DEFAULT_TIMEOUT, DEFAULT_SLEEP, DEFAULT_TIMEOUT_MESSAGE);
    }

    /**
     * Creates an instance that waits at most the specified time.
     * 
     * @param timeout
     *        the timeout in milliseconds.
     * @param timeoutMessage
     *        the message in the {@link TimedOut} exception
     */
    public Waiting (int timeout, String timeoutMessage) {
        this(timeout, DEFAULT_SLEEP, timeoutMessage);
    }

    /**
     * Creates an instance that waits at most the specified time and checks the condition after the
     * specified time.
     * 
     * @param timeout
     *        the timeout in milliseconds
     * @param sleep
     *        the time to sleep between calling {@link #until()}, in milliseconds
     */
    public Waiting (int timeout, int sleep) {
        this(timeout, sleep, DEFAULT_TIMEOUT_MESSAGE);
    }

    /**
     * Creates an instance that waits at most the specified time and checks the condition after the
     * specified time.
     * 
     * @param timeout
     *        the timeout in milliseconds
     * @param sleep
     *        the time to sleep between calling {@link #until()}, in milliseconds
     * @param timeoutMessage
     *        the message in the {@link TimedOut} exception
     */
    public Waiting (int timeout, int sleep, String timeoutMessage) {
        this.timeout = timeout;
        this.sleep = sleep;
        this.timeoutMessage = timeoutMessage;
    }

    /**
     * Waits until {@link #until()} returns true.
     * 
     * @throws TimedOut
     *         if {@link #until()} does not return true within in the timeout.
     * @throws Exception
     *         if {@link #until()} throws an exception
     */
    public void waitUntil ()
            throws TimedOut, Exception {
        waitUntil(this.timeout, this.sleep, this.timeoutMessage);
    }

    /**
     * Waits until {@link #until()} returns true.
     * 
     * @param timeoutMessage
     *        the timeout message, overrides the message in the constructor
     * @throws TimedOut
     *         if {@link #until()} does not return true within the timeout
     * @throws Exception
     *         if {@link #until()} throws an exception
     */
    public void waitUntil (String timeoutMessage)
            throws TimedOut, Exception {
        waitUntil(this.timeout, this.sleep, timeoutMessage);
    }

    /**
     * Waits until {@link #until()} returns true.
     * 
     * @param timeout
     *        the timeout in milliseconds, overrides the timeout in the constructor
     * @throws TimedOut
     *         if {@link #until()} does not return true within the timeout
     * @throws Exception
     *         if {@link #until()} throws an exception
     */
    public void waitUntil (int timeout)
            throws TimedOut, Exception {
        waitUntil(timeout, this.sleep, this.timeoutMessage);
    }

    /**
     * Waits until {@link #until()} returns true.
     * 
     * @param timeout
     *        the timeout in milliseconds, overrides the timeout in the constructor
     * @param timeoutMessage
     *        the timeout message, overrides the message in the constructor
     * @throws TimedOut
     *         if {@link #until()} does not return true within the timeout
     * @throws Exception
     *         if {@link #until()} throws an exception
     */
    public void waitUntil (int timeout, String timeoutMessage)
            throws TimedOut, Exception {
        waitUntil(timeout, this.sleep, timeoutMessage);
    }

    /**
     * Waits until {@link #until()} returns true.
     * 
     * @param timeout
     *        the timeout in milliseconds, overrides the timeout in the constructor
     * @param sleep
     *        the time between calls to {@link #until()}, in milliseconds, overrides the value
     *        defined in the constructor
     * @throws TimedOut
     *         if {@link #until()} does not return true within the timeout
     * @throws Exception
     *         if {@link #until()} throws an exception
     */
    public void waitUntil (int timeout, int sleep)
            throws TimedOut, Exception {
        waitUntil(timeout, sleep, this.timeoutMessage);
    }

    /**
     * Waits until {@link #until()} returns true.
     * 
     * @param timeout
     *        the timeout in milliseconds, overrides the timeout in the constructor
     * @param sleep
     *        the time between calls to {@link #until()}, in milliseconds, overrides the value
     *        defined in the constructor
     * @param timeoutMessage
     *        the timeout message, overrides the message in the constructor
     * @throws TimedOut
     *         if {@link #until()} does not return true within the timeout
     * @throws Exception
     *         if {@link #until()} throws an exception
     */
    public void waitUntil (int timeout, int sleep, String timeoutMessage)
            throws TimedOut, Exception {
        int waited = 0;
        while (true) {
            if (this.until())
                break;
            if (timeout > 0 && waited >= timeout) {
                throw new TimedOut(timeoutMessage);
            }
            try {
                Thread.sleep(sleep);
            }
            catch (InterruptedException e) {}
            waited += sleep;
        }
    }

    /**
     * Indicates that the condition is true.
     * 
     * @return true if the condition is true
     * @throws Exception
     *         if an error occurs while checking the condition
     */
    public abstract boolean until ()
            throws Exception;

    /**
     * Exception thrown when the condition does not become true within the timeout.
     */
    public class TimedOut
            extends Exception {

        private static final long serialVersionUID = 1L;

        public TimedOut (String message) {
            super(message);
        }
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Timer Skipping BeepTimer Skipping Beep
2.Timer Schedule a task that executes once every secondTimer Schedule a task that executes once every second
3.Use java.util.Timer to schedule a task to execute once 5 seconds have passedUse java.util.Timer to schedule a task to execute once 5 seconds have passed
4.Timer utilities
5.Timer and TimerTask Classes
6.Pause and start a timer task
7.Create a Timer object
8.Swing also provide a Timer class. A Timer object will send an ActionEvent to the registered ActionListener.
9.Schedule a task by using Timer and TimerTask.
10.Scheduling a Timer Task to Run Repeatedly
11.Create a scheduled task using timer
12.extends TimerTask to create your own task
13.A simple implementation of the Java 1.3 java.util.Timer API
14.Scheduling a Timer Task to Run at a Certain Time
15.Class encapsulating timer functionality
16.Timeout Observer
17.A pool of objects that should only be used by one thread at a time
18.A class that allows a programmer to determine the amount of time spend doing certain routines
19.All times in this Timer object are in milliseconds. The timer starts from the moment of it's creation.
20.Thread Timer
21.Cancel Aware Timer
22.HRTimer is a simple system-wide timer facility using a singleton Timer, with additional instrumentation.
23.Used for timing events with millisecond precision.