Server Settings - Scheduled Tasks

Create, manage, and monitor automated tasks for ColdFusion operations

Overview

The Scheduled Tasks page in ColdFusion Administrator enables you to automate recurring operations such as generating reports, clearing caches, processing batch jobs, calling APIs, and maintaining data. Scheduled tasks provide cron-like functionality within ColdFusion, allowing you to execute ColdFusion pages or HTTP requests at specified intervals without manual intervention.

This powerful feature eliminates the need for external cron jobs or Windows Task Scheduler for many automation scenarios. Tasks can be scheduled to run once, daily, weekly, monthly, or on custom intervals. ColdFusion maintains task history, logs execution results, and provides tools for monitoring and troubleshooting scheduled operations.

Creating Scheduled Tasks

Task Name

  • Purpose: Unique identifier for the scheduled task
  • Requirements: Must be unique across all scheduled tasks
  • Best Practice: Use descriptive names that indicate purpose (e.g., "DailyReportGeneration", "HourlyDataSync")
  • Naming Convention: Consider prefixes for categorization (REPORT_, MAINT_, SYNC_)
  • Character Restrictions: Avoid special characters; use alphanumeric and underscores

Task Type

  • URL Execution: Execute a ColdFusion page via HTTP request (most common)
  • File Path: Directly execute a CFM file on the server filesystem
  • URL Advantages: Can include query parameters, authentication, test externally
  • File Path Advantages: Faster execution, no HTTP overhead, not exposed to network
  • Security Note: File path tasks bypass web server security; ensure proper authorization

URL or File Path

  • URL Format: Full URL including protocol (http://localhost/tasks/daily-report.cfm)
  • Query Parameters: Include parameters for task configuration (url?mode=full&type=pdf)
  • File Path Format: Absolute server path (/var/www/html/tasks/cleanup.cfm)
  • Localhost Preference: Use localhost URLs to avoid external network dependencies
  • Testing: Verify URL/path is accessible before creating task
  • Authentication: Consider username/password if URL requires authentication

Username and Password

  • Purpose: HTTP authentication credentials for protected URLs
  • Basic Authentication: Supports HTTP Basic Auth
  • Security Risk: Credentials stored in clear text in CF configuration
  • Best Practice: Use task-specific accounts with minimal permissions
  • Alternative: Use IP-based authentication or secret tokens in URL
  • Audit: Regularly review and rotate task credentials

Port

  • Default: 80 (HTTP) or 443 (HTTPS)
  • Custom Ports: Specify if running on non-standard port
  • Recommendation: Use standard ports unless specific requirement exists

Proxy Server

  • Purpose: Route task requests through proxy server
  • Format: proxyhost:proxyport
  • Use Case: Required when server must use proxy for external URLs
  • Internal Tasks: Usually not needed for localhost URLs

Schedule Types

One-Time Execution

  • Purpose: Run task once at specific date and time
  • Use Cases: Scheduled maintenance, one-time migration, event-triggered action
  • Configuration: Specify exact date and time for execution
  • Status: Task automatically disabled after execution
  • Verification: Check task history to confirm execution
  • Best Practice: Delete or archive completed one-time tasks

Recurring - Daily

  • Purpose: Execute task every day at specified time(s)
  • Single Time: Run once per day (e.g., 2:00 AM)
  • Multiple Times: Run multiple times per day (e.g., 6:00 AM, 12:00 PM, 6:00 PM)
  • Use Cases: Daily reports, nightly backups, end-of-day processing
  • Time Zone: Uses server time zone; document for multi-region deployments
  • Frequency: Configure interval in hours and minutes between executions

Recurring - Weekly

  • Purpose: Execute task on specific days of the week
  • Day Selection: Choose one or more days (Monday, Wednesday, Friday)
  • Time Configuration: Specify execution time for selected days
  • Use Cases: Weekly reports, weekend maintenance, mid-week updates
  • Best Practice: Avoid scheduling resource-intensive tasks during business hours

Recurring - Monthly

  • Purpose: Execute task on specific day(s) of each month
  • Day Selection: Specify day of month (1-31)
  • Multiple Days: Run on multiple days (1st and 15th for bi-monthly)
  • Month-End Consideration: Be careful with days 29-31 (not all months have these days)
  • Last Day Option: Some versions support "last day of month" option
  • Use Cases: Monthly reports, billing processes, monthly maintenance

Custom Interval

  • Purpose: Execute task at specific intervals (hours, minutes)
  • Configuration: Set interval in hours and/or minutes (e.g., every 30 minutes)
  • Start Time: Specify when interval counting begins
  • End Time: Optional end time to stop execution
  • Use Cases: Data synchronization, cache warming, health checks
  • Performance Impact: Frequent intervals can impact server performance
  • Recommendation: Use minimum interval of 5 minutes unless specifically required

Task Configuration Options

Start Date and Time

  • Purpose: When task execution should begin
  • Default: Immediately or at next scheduled interval
  • Future Date: Schedule task to start at future date
  • Use Case: Deploy task now but activate later
  • Best Practice: Set start date for new production tasks to control activation

End Date and Time

  • Purpose: When task execution should stop
  • Optional: Leave blank for indefinite execution
  • Use Cases: Temporary data collection, limited-time processing, phased deprecation
  • Automatic Disable: Task automatically disabled after end date
  • Cleanup: Review and remove tasks after end date passes

Request Timeout

  • Purpose: Maximum execution time for task (in seconds)
  • Default: Uses server-wide request timeout setting
  • Recommendation: Set based on expected task duration plus buffer
  • Long-Running Tasks: Increase timeout for batch processing, reports
  • Safety Net: Prevents runaway tasks from consuming resources indefinitely
  • Monitoring: Tasks timing out indicate performance issues or insufficient timeout
  • Typical Values: 300 seconds (5 min) for reports, 3600 (1 hour) for batch jobs

Publish

  • Purpose: Save task output to a file
  • File Path: Specify absolute path for output file
  • Use Cases: Save generated reports, archive output, enable retrieval
  • Overwrite: Each execution overwrites previous output
  • Best Practice: Use timestamped filenames to preserve history
  • Permissions: Ensure ColdFusion has write permissions to output directory

Enable on Server Startup

  • Purpose: Activate task immediately when ColdFusion starts
  • Default: Enabled
  • Disabled Option: Keep task defined but not active
  • Use Case: Temporarily disable problematic tasks
  • Testing: Disable tasks during development/testing

Resolve URL

  • Purpose: Follow HTTP redirects when executing task
  • Default: Enabled
  • Use Case: Tasks targeting URLs that may redirect
  • Security: Be cautious with external URLs that might redirect maliciously

Chain Tasks

  • Purpose: Execute another task after this task completes
  • Chaining: Create dependencies between tasks
  • Use Case: Sequential processing (process data, then generate report)
  • Limitation: No built-in error handling between chained tasks
  • Alternative: Consider single task that calls multiple operations

Task Management

Enabling and Disabling Tasks

  • Enable: Activate task for scheduled execution
  • Disable: Pause task without deleting configuration
  • Use Cases: Troubleshooting, maintenance, testing
  • Status Indicator: Administrator shows enabled/disabled status
  • Best Practice: Disable tasks before making changes

Editing Tasks

  • Modification: Click task name to edit configuration
  • Active Tasks: Can edit running tasks (changes apply after current execution)
  • Testing: Test changes in development before production
  • Documentation: Maintain change log for task modifications

Deleting Tasks

  • Permanent: Removes task and all configuration
  • History: Task history is also deleted
  • Best Practice: Disable first, then delete after verification period
  • Backup: Export task configuration before deletion

Run Now

  • Purpose: Execute task immediately regardless of schedule
  • Use Cases: Testing, manual trigger, recovery from failures
  • Synchronous: Administrator waits for task completion (or timeout)
  • Status Display: Shows execution result immediately
  • Best Practice: Use for testing before relying on schedule

Viewing Task History

  • Access: Click task name and view history section
  • Information: Execution date/time, status, duration, output size
  • Status Values: Success, Error, Timeout
  • Retention: Limited history kept (typically last 10-20 executions)
  • Monitoring: Review regularly to identify patterns or issues

Task History and Logging

Execution History

  • Records Kept: Last executions with status and duration
  • Success Indicator: Green check or "OK" status
  • Failure Indicator: Red X or "Error" status
  • Details: Click execution to view detailed results
  • Output: View or download task output if published

Log Files

  • Location: ColdFusion logs directory (cfusion/logs/scheduled.log)
  • Information: Task start, completion, errors, warnings
  • Format: Standard CF log format with timestamp and severity
  • Monitoring: Parse logs for automated alerting
  • Rotation: Logs rotate based on server logging settings

Application Logging

  • Task Code: Use cflog within scheduled task for custom logging
  • Log File: Write to dedicated log file for task operations
  • Error Tracking: Log errors with context for troubleshooting
  • Metrics: Log processing counts, durations, results

Error Handling and Notifications

Built-in Error Handling

  • HTTP Errors: Automatically logged if URL returns error status
  • Timeouts: Logged when task exceeds request timeout
  • Connection Errors: Network or server unavailability logged
  • Status: Task marked as failed in history
  • Retry: No automatic retry; task runs again at next scheduled time

Custom Error Handling

  • Try/Catch: Implement error handling in task code
  • Logging: Log errors with stack traces for debugging
  • Notifications: Send email/alerts on critical errors
  • Graceful Degradation: Handle partial failures appropriately
  • Return Codes: Use HTTP status codes to indicate success/failure

Email Notifications

  • Implementation: Add email code to task for failures
  • Threshold: Alert after consecutive failures to reduce noise
  • Information: Include error details, timestamp, task name
  • Recipients: Send to appropriate support team or monitoring system

Integration with Monitoring

  • External Monitoring: Configure health check to verify task execution
  • Dead Man's Switch: Alert if task hasn't run in expected timeframe
  • Log Monitoring: Parse scheduled.log for error patterns
  • APM Integration: Use FusionReactor or similar to track task performance

Best Practices

Production Environment

  • Use descriptive task names that clearly indicate purpose
  • Set appropriate request timeouts with reasonable buffers
  • Implement error handling and logging in all task code
  • Configure email notifications for critical task failures
  • Schedule resource-intensive tasks during off-peak hours
  • Use localhost URLs to avoid external network dependencies
  • Document all scheduled tasks including purpose and dependencies
  • Review task history regularly to identify failures or performance issues
  • Set end dates for temporary tasks to prevent orphaned jobs
  • Maintain inventory of all scheduled tasks across servers

Development and Testing

  • Test tasks using "Run Now" before relying on schedule
  • Verify task execution manually before deploying to production
  • Use different task names or schedules in dev/staging/production
  • Disable production-like schedules in development environments
  • Test error handling and timeout scenarios
  • Verify task output and logging before production deployment

Security Considerations

  • Secure task URLs with authentication or IP restrictions
  • Use task-specific accounts with minimal required permissions
  • Avoid storing sensitive credentials in task configuration
  • Consider secret tokens in URLs instead of username/password
  • Restrict access to scheduled task administration
  • Regularly audit task configurations and credentials
  • Use HTTPS for task URLs when possible
  • Implement IP whitelisting for task endpoints
  • Log all task executions for security auditing

Performance and Monitoring

  • Monitor task execution duration to identify performance degradation
  • Avoid overlapping executions of same task (use adequate intervals)
  • Use minimum 5-minute intervals for frequent tasks
  • Implement locking mechanisms for tasks that shouldn't run concurrently
  • Review server logs for task-related errors or warnings
  • Track task execution metrics (duration, records processed, success rate)
  • Set up alerts for consecutive task failures
  • Use external monitoring to verify critical tasks are running

Maintenance and Documentation

  • Document each task's purpose, schedule, and dependencies
  • Maintain change log for task configuration modifications
  • Review and clean up obsolete tasks quarterly
  • Export task configurations for backup and disaster recovery
  • Include scheduled tasks in application documentation
  • Plan for task migration during server upgrades

Common Issues and Troubleshooting

Tasks Not Running at Scheduled Time

  • Symptom: Task doesn't execute at expected time
  • Causes: Task disabled, server time incorrect, ColdFusion service stopped
  • Verification: Check task is enabled, verify server time, check CF service status
  • Logs: Review scheduled.log for execution records or errors
  • Testing: Use "Run Now" to verify task can execute
  • Time Zone: Ensure server time zone matches expected schedule

Tasks Timing Out

  • Symptom: Task marked as failed with timeout error
  • Cause: Task execution exceeds configured timeout
  • Solution: Increase request timeout or optimize task code
  • Investigation: Review task code for performance bottlenecks
  • Database Queries: Check for slow queries or missing indexes
  • External Calls: Verify external services are responsive

Authentication Errors

  • Symptom: 401 or 403 HTTP errors in task history
  • Cause: Incorrect credentials or insufficient permissions
  • Solution: Verify username/password or use alternative authentication
  • IP Restrictions: Whitelist server IP for task URLs
  • Session Issues: Ensure task URL doesn't require session state

Tasks Running Multiple Times

  • Symptom: Task executes more than once at scheduled time
  • Cause: Previous execution hasn't completed when next is triggered
  • Solution: Increase execution interval or optimize task performance
  • Locking: Implement named locks to prevent concurrent executions
  • Detection: Check task history for overlapping executions

Connection Refused Errors

  • Symptom: Task fails with connection refused error
  • Cause: Web server not running or URL incorrect
  • Verification: Test URL in browser or curl from CF server
  • Localhost: Ensure localhost resolves and web server listens on specified port
  • Firewall: Verify no firewall blocking localhost connections

Tasks Not Appearing After Server Restart

  • Symptom: Scheduled tasks missing after CF restart
  • Cause: Configuration file corruption or migration issue
  • Location: Tasks stored in neo-cron.xml (cfusion/lib directory)
  • Recovery: Restore from backup or recreate tasks
  • Prevention: Regularly backup neo-cron.xml file

Output File Not Created

  • Symptom: Publish enabled but file not written
  • Cause: Permission errors or invalid path
  • Solution: Verify CF has write permissions to output directory
  • Path: Ensure absolute path is correct and directory exists
  • Testing: Use simple test task to verify publish functionality

Programmatic Task Management

Use the cfschedule tag to create, manage, and execute scheduled tasks programmatically.

Creating Tasks Programmatically

Creating and Managing Scheduled Tasks
// Create or update a scheduled task
schedule action="update"
  task="MyScheduledTask"
  operation="HTTPRequest"
  url="http://localhost/tasks/my-task.cfm"
  startDate="01/01/2025"
  startTime="2:00 AM"
  interval="daily"
  requestTimeout="300";

// Run existing task immediately
schedule action="run" task="MyScheduledTask";

// Delete task
schedule action="delete" task="MyScheduledTask";
<!--- Create or update a scheduled task --->
<cfschedule
  action="update"
  task="MyScheduledTask"
  operation="HTTPRequest"
  url="http://localhost/tasks/my-task.cfm"
  startDate="01/01/2025"
  startTime="2:00 AM"
  interval="daily"
  requestTimeout="300">

<!--- Run existing task immediately --->
<cfschedule
  action="run"
  task="MyScheduledTask">

<!--- Delete task --->
<cfschedule
  action="delete"
  task="MyScheduledTask">

Listing All Tasks

List All Scheduled Tasks
// Get list of all scheduled tasks
schedule action="list" result="tasks";

// Display task information
writeDump(tasks);

// Loop through tasks
for (task in tasks) {
  writeOutput("Task: #task.task# - Status: #task.status#<br>");
}
<!--- Get list of all scheduled tasks --->
<cfschedule
  action="list"
  result="tasks">

<!--- Display task information --->
<cfdump var="#tasks#">

<!--- Loop through tasks --->
<cfloop query="tasks">
  <cfoutput>Task: #tasks.task# - Status: #tasks.status#<br></cfoutput>
</cfloop>

Advanced Patterns

Distributed Task Management

  • In clustered environments, tasks execute on all servers by default
  • Use database flags to ensure single execution across cluster
  • Implement leader election for critical tasks
  • Consider centralized scheduler for complex orchestration

Task Coordination

  • Use database tables to track task status and prevent conflicts
  • Implement named locks for tasks that modify shared resources
  • Create task dependencies using database flags or file markers
  • Use message queues for complex task workflows

Health Monitoring

  • Create heartbeat tasks that update database timestamps
  • Monitor last execution time to detect stuck or failing tasks
  • Implement watchdog tasks that verify other tasks are running
  • Use external monitoring to alert on task failures

Related Resources