Jump to content

ConditionalLoop class


Recommended Posts

Posted (edited)

A quick example of a ConditionalLoop class. The API one is great and I suggest you use that one, this is more for learning purposes.

package org.bjornkrols.conditional;

import org.bjornkrols.imported.MilliTimer;

/**
 * @author 		Bjorn Krols (Botre)
 * @version		0.1
 * @since		March 26, 2015
 */

public abstract class ConditionalLoop extends Thread {

	/**
	 * This loop's timer (millisecond precision).
	 */
	private MilliTimer timer;
	
	/**
	 * The maximum (exclusive) time of looping, in milliseconds, after which the loop will be broken.
	 */
	private int timeout;
	
	public ConditionalLoop(final int timeout) {
		setDaemon(true);
		setTimeout(timeout);
	}
	
	/**
	 * A no-argument constructor with a default timeout of 10 seconds.
	 */
	public ConditionalLoop() {
		this(10000);
	}
	
	@Override
	public void run() {
		preLoop();
		while (condition()) {
			if (timer.getElapsedMilliSeconds() > timeout) {
				onTimeout();
				break;
			}
			try {
				Thread.sleep(onLoop());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		postLoop();
	}
	
	/**
	 * @return Whether to continue to loop.
	 */
	public abstract boolean condition();
	
	/**
	 * Executes before the loop starts.
	 */
	public void preLoop() { 
		timer = new MilliTimer();
	};
	
	/**
	 * The actual loop.
	 * 
	 * @return The time to sleep for, in milliseconds, after each iteration.
	 */
	public abstract int onLoop();
	
	/**
	 * Executes after the loop.
	 */
	public void postLoop() { };
	
	/**
	 * Executes when the loop has timed out.
	 */
	public void onTimeout() { }
	
	/**
	 * Sets the timeout (in milliseconds).
	 *
	 * @param milliseconds The time out (in milliseconds).
	 */
	public void setTimeout(int milliseconds) {
		timeout = milliseconds;
	}
	
}
Edited by Botre
  • Like 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...