Last active
August 29, 2015 13:57
-
-
Save GameplayJDK/9709226 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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