Skip to content

Instantly share code, notes, and snippets.

@rahulsom rahulsom/Foo.groovy
Created Jul 19, 2012

Embed
What would you like to do?
Reloading Scripts in groovy, Erlang style

This script demonstrates reloading a script. So if you're running something in a loop, and want the ability to modify the code at runtime, this is your best bet.

I still have to figure out how to make it an annotation that you apply at the top of the script and have the whole script run in a loop.

<script src="https://gist.github.com/3145120.js?file=Foo.groovy"></script>
public class ReloadingScript {
/**
* The Class of the script
*/
Class clazz
/**
* Runs the script in a Erlang-ish loop
*
* @param methodName The method in the script to run
* @param loops The number of times to run it. -1 for infinite loop.
* @param sleep The number of seconds to sleep between runs. >= 0.
*/
public void runInLoop(String methodName, int loops, int sleep) {
assert sleep >= 0
String scriptFullName = clazz.protectionDomain.codeSource.location.path
def scriptDir = new File(scriptFullName).parent
def scriptName = new File(scriptFullName).name
def engine = new GroovyScriptEngine(scriptDir)
engine.config.minimumRecompilationInterval = 0
if (loops >= 0) {
loops.times {
executeScript(engine, scriptName, methodName, sleep)
}
} else if (loops < 0) {
while (true) {
executeScript(engine, scriptName, methodName, sleep)
}
}
}
private void executeScript(engine, String scriptName, String methodName, int sleep) {
clazz = engine.loadScriptByName(scriptName)
def scriptInstance = (GroovyObject) clazz.newInstance()
scriptInstance.invokeMethod(methodName, [] as Object[])
Thread.sleep(sleep)
}
}
void foo() {
println "K"
}
new ReloadingScript(clazz: getClass()).runInLoop('foo', 20, 2000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.