Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Last active August 29, 2015 14:05
Show Gist options
  • Save bdkosher/23389d841a874c52eda7 to your computer and use it in GitHub Desktop.
Save bdkosher/23389d841a874c52eda7 to your computer and use it in GitHub Desktop.
Groovy script that can execute the provided command repeatedly at a fixed interval.
import java.util.concurrent.*
def execSingle = { String cmd, out, showTs ->
if (showTs) out << "${System.currentTimeMillis()}: "
out << cmd.execute().in
}
def exec = { cmdStrOrList, out, showTs ->
switch (cmdStrOrList) {
case String:
execSingle(cmdStrOrList, out, showTs)
case List:
cmdStrOrList.each { line -> execSingle(line, out, showTs) }
}
}
def execRepeatedly = { cmdStrOrList, out, showTs, intervalMs ->
def runnableExec = { ->
exec(cmdStrOrList, out, showTs)
} as Runnable
ExecutorService service = Executors.newScheduledThreadPool(1)
service.scheduleAtFixedRate(runnableExec, 0, intervalMs, TimeUnit.MILLISECONDS)
service.awaitTermination(365, TimeUnit.DAYS) // technically, we should await forever
}
def (showExecTime, interval, output, commandList) = new CliBuilder(usage: 'groovy ExecutIOr.groovy file/to/capture/command/output command(s)').with {
h('prints usage help', longOpt:'help')
o('output command results to file', args:1, argName: 'file', longOpt:'outfile')
r('interval of ms between repeated calls (0 to disable repeat)', args:1, argName:'millis', longOpt:'repeat')
t('show timestamp on execution', longOpt:'timestamp')
parse(args).with {
if (h || !arguments()) {
usage()
System.exit(0)
} else {
long interval = (r ? r as long : 0)
def outTo = System.out
if (o) {
def file = new File(o)
if (file.exists() && file.isDirectory()) {
println "Cannot send output to a directory ($file)"
System.exit(0)
} else if (file.parentFile == null) {
file = new File(new File('.'), o)
} else {
file.parentFile.mkdirs()
}
println "Sending output to $file"
outTo = file
}
[t, interval, outTo, arguments()]
}
}
}
if (interval > 0) {
execRepeatedly(commandList, output, showExecTime, interval)
} else {
exec(commandList, output, showExecTime)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment