Task Services
CommandBox Task Runners are a powerful way to accomplish CLI scripting. You may have a task you'd like to run as a daemon so it's always executing. This could be a message queue consumer, a scheduled task, or a file system watcher. It is important that your tasks never exits, but always stays running forever. Make sure you use an uninterruptible method of blocking the task such as sleep() so that when the service is shutdown, the interrupt signal will stop the task cleanly.
Here is example of a task that uses sleep to stay running, but any command that stops when you press Ctrl-C from the command line will work (such as a file system watcher).
Create an empty task runner like so:
1
task create --open
Copied!
And now put some code into it. The while( true ) loop makes it run forever (daemon) and the sleep will throw an exception when the thread is interrupted so it can be stopped.
task.cfc
1
component {
2
3
function run() {
4
try{
5
while( true ) {
6
print.line( "still running!" ).toConsole()
7
sleep( 5000 );
8
}
9
// Catching this will give us a clean shutdown so the service doesn't show as failed
10
} catch( java.lang.InterruptedException e ) {
11
print.line( 'Task interrupted ...' ).toConsole();
12
} finally {
13
// Any logic needed to clean up here
14
}
15
16
}
Copied!
You can test your task like so:
1
task run
Copied!
Hit Ctrl-C to stop it. Now, create a service out of.
1
task service create --start
Copied!
Warning: if you don't create a task that keeps running forever, the service will just restart your task every time it stops (the default exit action is restart. This will use a lot more CPU than you want!
Last modified 28d ago
Copy link
Edit on GitHub