Safe Scheduled Tasks

Automation that won't come back to bite you

Configure ColdFusion scheduled tasks with proper security controls, timeouts, and monitoring to ensure reliable automation without compromising server security.

Scheduled Task Security

Scheduled tasks can become vectors for security vulnerabilities if not properly configured:

  • Use allowlisted output directories defined in pathfilter.json to restrict file operations
  • Never allow tasks to write output to arbitrary file system locations
  • Configure tasks to run with minimal privileges necessary for their function
  • Validate and sanitize any parameters passed to scheduled tasks
  • Log all task execution details to maintain a complete audit trail

Path Filtering for Task Output

Since the security updates that introduced pathfilter.json (in <cf_home>/lib), a task with Publish > Save output to a file enabled no longer runs unless its output path is allowed in the schedulerexecutionpaths key. Output files are also limited to .txt and .log extensions by default:

Pathfilter Configuration
// <cf_home>/lib/pathfilter.json (other keys omitted)
// Semicolon-separated: file;  dir/*;  dir/**;  !blocked/**;
{
  "schedulerexecutionpaths": "/var/app/reports/**;"
}
Important: The value is a single semicolon-separated string, not an array. A path ending in /* allows a directory's files, /** adds subdirectories, and a leading ! blocks a path (precedence decreases from left to right). Restart ColdFusion after editing the file. Adobe's update notes warn that an update can overwrite custom pathfilter.json entries, so back the file up before updating (the update also keeps a copy under hf-updates). Separately, some updates removed tasks with Save output to a file from neo-cron.xml, so back up neo-cron.xml too.

Timeouts and Error Handling

You should always configure appropriate timeouts to prevent hung tasks from consuming server resources indefinitely:

  • Set an explicit request timeout value for each task based on expected execution time
  • Configure retry logic to handle transient failures gracefully
  • Implement exponential backoff between retry attempts to avoid overwhelming resources
  • Send alerts to operations teams when tasks experience repeated failures
  • Log comprehensive details including task start time, end time, duration, and final status
Task Timeout and Error Handling
<cfsetting requestTimeout="300"> <!--- 5 minutes --->
<cfset startTick = getTickCount()>

<cftry>
    <!--- Task logic here --->
    <cflog file="scheduled_tasks"
        type="information"
        text="Task completed: taskName=dailyReport, duration=#getTickCount() - startTick#ms">

    <cfcatch>
        <cflog file="scheduled_tasks"
            type="error"
            text="Task failed: taskName=dailyReport, error=#cfcatch.message#">

        <!--- Send alert to ops team --->
        <cfmail to="ops@example.com" from="cf@example.com" subject="Task Failed">
            Scheduled task failed: #cfcatch.message#
        </cfmail>
    </cfcatch>
</cftry>
setting requestTimeout="300"; // 5 minutes
startTick = getTickCount();

try {
    // Task logic here
    writeLog(
        file = "scheduled_tasks",
        type = "information",
        text = "Task completed: taskName=dailyReport, duration=#getTickCount() - startTick#ms"
    );
} catch (any e) {
    writeLog(
        file = "scheduled_tasks",
        type = "error",
        text = "Task failed: taskName=dailyReport, error=#e.message#"
    );

    // Send alert to ops team
    cfmail(
        to = "ops@example.com",
        from = "cf@example.com",
        subject = "Task Failed"
    ) {
        writeOutput("Scheduled task failed: #e.message#");
    }
}

Clustering Considerations

In clustered environments, you need to prevent duplicate task execution across multiple nodes:

  • Scheduler Clustering (Enterprise): Use Enable Cluster Setup on the Scheduled Tasks page (it needs a data source; create the tables from one node only) and tick Cluster on each task. Clustering works only with the JDBC job store, provides load balancing and job fail-over, and requires the same system time on all clustered servers
  • External Scheduler: Use cron or Windows Task Scheduler to invoke tasks on only one designated node
  • Database Locking: Acquire a database lock before task execution to prevent other nodes from running the same task
  • Distributed Lock: Use Redis or a similar distributed system to manage cluster-wide locks
  • Leader Election: Implement leader election so that only the leader node executes scheduled tasks
Database Lock Pattern for Clustering
<!--- Example: Database lock pattern --->
<cfquery result="getLock" datasource="mydb">
    UPDATE task_locks
    SET locked_by = <cfqueryparam value="#server.coldfusion.rootDir#">,
        locked_at = <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">
    WHERE task_name = <cfqueryparam value="dailyReport">
      AND (locked_at IS NULL OR locked_at < <cfqueryparam value="#dateAdd('n', -10, now())#" cfsqltype="cf_sql_timestamp">)
</cfquery>

<cfif getLock.recordCount GT 0>
    <!--- We got the lock, run task --->
    <cftry>
        <!--- Task logic --->
        <cffinally>
            <!--- Release lock --->
            <cfquery datasource="mydb">
                UPDATE task_locks SET locked_by = NULL, locked_at = NULL
                WHERE task_name = <cfqueryparam value="dailyReport">
            </cfquery>
        </cffinally>
    </cftry>
<cfelse>
    <!--- Another node is running this task --->
    <cflog file="scheduled_tasks" type="information"
        text="Task skipped - already running on another node">
</cfif>
// Example: Database lock pattern
queryExecute("
    UPDATE task_locks
    SET locked_by = :rootDir,
        locked_at = :now
    WHERE task_name = :taskName
      AND (locked_at IS NULL OR locked_at < :expiry)
", {
    rootDir: {value: server.coldfusion.rootDir, cfsqltype: "cf_sql_varchar"},
    now: {value: now(), cfsqltype: "cf_sql_timestamp"},
    taskName: {value: "dailyReport", cfsqltype: "cf_sql_varchar"},
    expiry: {value: dateAdd('n', -10, now()), cfsqltype: "cf_sql_timestamp"}
}, {datasource: "mydb", result: "getLock"});

if (getLock.recordCount > 0) {
    // We got the lock, run task
    try {
        // Task logic
    } finally {
        // Release lock
        queryExecute("
            UPDATE task_locks SET locked_by = NULL, locked_at = NULL
            WHERE task_name = :taskName
        ", {
            taskName: {value: "dailyReport", cfsqltype: "cf_sql_varchar"}
        }, {datasource: "mydb"});
    }
} else {
    // Another node is running this task
    writeLog(
        file = "scheduled_tasks",
        type = "information",
        text = "Task skipped - already running on another node"
    );
}

Monitoring and Alerting

You should implement comprehensive monitoring to ensure scheduled tasks are running reliably:

  • Track task execution duration using the Performance Monitoring Toolset (PMT)
  • Configure alerts to notify you immediately of task failures or timeouts
  • Monitor for tasks that stop running entirely and miss their scheduled execution times
  • Create a dashboard that shows the last run time and current status for all tasks
  • Perform trend analysis on task performance over time to identify degradation

Best Practices

  • Use database-driven schedules instead of the CF Administrator Scheduled Tasks page so you can version control your task configurations
  • Store all task configuration and code in version control for auditability and rollback capability
  • Always test scheduled tasks thoroughly in staging environments before deploying to production
  • Implement tasks to be idempotent so they're safe to run multiple times without adverse effects
  • Consider using message queues for long-running background work instead of scheduled tasks
  • Document all task dependencies and data flow to help with troubleshooting and maintenance

Scheduled Tasks Checklist

  • Output directories allowlisted in pathfilter.json
  • Request timeout configured for each task
  • Error handling and logging implemented
  • Retry logic for transient failures
  • Cluster-safe execution (locks or external scheduler)
  • Monitoring and alerting configured
  • Tasks documented with purpose and dependencies
  • Test coverage for task logic

Gotchas

  • Tasks run with same permissions as ColdFusion server - limit file system access
  • Missed schedules need explicit handling: A run counts as misfired when it misses its firing time by more than 60 seconds (for example, the scheduler was down or no threads were free). Set On Misfire (FIRE_NOW or INVOKEHANDLER for the handler's onMisfire method) and On Exception with Retry Count, and check scheduler.log, where misfires are logged. Misfire, exception, and retry handling, like clustering, is Enterprise only; Standard reports that advanced scheduling is not available in this edition
  • Long-running tasks can accumulate if frequency exceeds duration
  • Task configuration in Administrator not version controlled - use database
  • Cluster without coordination runs tasks on all nodes. In Enterprise, use the scheduler's cluster setup (JDBC job store, same system time on all nodes); in Standard, use locking or an external scheduler
  • Pathfilter changes require ColdFusion restart to take effect

Need Help?

Convective can help design and implement reliable scheduled task architectures.

Find out more
ColdFusion Scheduled Tasks - Secure Automation and Clustering Guide | CFGuide