Jump to content

ConditionalLoop class


Botre

Recommended Posts

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
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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