Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package de.GameplayJDK.TimerAPI.API;
import java.util.concurrent.Callable;
/**
*
* @author GameplayJDK
*
*/
public class TimedFunctionCall {
private Callable<Object> function;
private Object[] args;
private int sleep;
/**
*
* @param function
* @param sleep
*/
public TimedFunctionCall(Callable<Object> function, int sleep) {
this.function = function;
this.args = null;
this.sleep = sleep;
}
/**
*
* @param function
* @param args
* @param sleep
*/
public TimedFunctionCall(Callable<Object> function, Object[] args, int sleep) {
this.function = function;
this.args = args;
this.sleep = sleep;
}
private boolean active = false;
/**
*
* @return
*/
public TimedFunctionCall call() {
this.active = true;
this.runFunction();
return this;
}
/**
*
* @return
*/
public TimedFunctionCall callNow() {
this.active = false;
doTimedCall();
return this;
}
/**
*
* @return
*/
public TimedFunctionCall cancel() {
this.active = false;
return this;
}
private void runFunction() {
new Runnable() {
@Override
public void run() {
long starttime = System.currentTimeMillis();
long waittime = sleep * 1000;
while (active) {
long currenttime = System.currentTimeMillis();
if (currenttime >= starttime + waittime) {
doTimedCall();
break;
}
}
}
};
}
private void doTimedCall() {
try {
execute(this.args, this.function);
} catch (Exception e) {
e.printStackTrace();
}
this.active = false;
}
/**
*
* @param args
* @param method
* @return
* @throws Exception
*/
private static Object execute(Object[] args, Callable<Object> method) throws Exception {
return method.call();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment