# 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. &#x20;

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:

```bash
task create --open
```

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.

{% code title="task.cfc" %}

```javascript
component {
    
  function run() {
    try{
      while( true ) {
        print.line( "still running!" ).toConsole()
        sleep( 5000 );
      }
    // Catching this will give us a clean shutdown so the service doesn't show as failed
    } catch( java.lang.InterruptedException e ) {
      print.line( 'Task interrupted ...' ).toConsole();
    } finally {
      // Any logic needed to clean up here
    }

}
```

{% endcode %}

You can test your task like so:

```bash
task run
```

Hit Ctrl-C to stop it.  Now, create a service out of.

```bash
task service create --start
```

{% hint style="warning" %}
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!
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://commandbox-service-manager.ortusbooks.com/task-services.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
