Jump to content

ConditionalSleep class


Botre

Recommended Posts

A quick example of a ConditionalSleep 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 16, 2015
 */

public abstract class ConditionalSleep {
	
	/**
	 * The time in milliseconds to sleep for per loop.
	 */
	private final int sleep;
	
	/**
	 * The maximum (exclusive) time of sleep, in milliseconds, after which the sleep loop will be broken.
	 */
	private final int timeout;
	
	/**
	 * @param sleep		The time in milliseconds to sleep for per loop.
	 * @param timeout	The maximum (exclusive) time of sleep in milliseconds after which the sleep loop will be broken.
	 */
	public ConditionalSleep(final int sleep, final int timeout) {
		this.sleep = sleep;
		this.timeout = timeout;
	}
	
	/**
	 * @return Whether to continue to sleep.
	 */
	public abstract boolean condition();
	
	/**
	 * Sleeps until the condition returns false or the timeout is reached.
	 */
	public void sleep() {
		MilliTimer timer = new MilliTimer();
		while (condition() && timer.getElapsedMilliSeconds() < timeout) {
			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

Implementation example:

// Wait while moving or making fire.
			new ConditionalSleep(300, 5000) {
				@Override
				public boolean condition() {
					return script.myPlayer().isMoving() || script.myPlayer().getAnimation() == FIREMAKING_ANIMATION;
				}
			}.sleep();
Edited by Botre
  • Like 3
Link to comment
Share on other sites

  • 2 weeks later...

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...