Skip to main content

Scheduled Functions

Automate recurring tasks, maintenance operations, and time-based workflows with ekoDB's built-in scheduler.

Background Execution

Scheduled functions run automatically in the background without blocking database operations.

Quick Start

# 1. Create a function to schedule
curl -X POST https://{EKODB_API_URL}/api/functions \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"label": "daily_cleanup",
"description": "Remove old log records",
"functions": [{
"type": "Delete",
"collection": "logs",
"filter": {
"field": "created_at",
"operator": "LessThan",
"value": "{{cutoff_date}}"
}
}]
}'

# 2. Schedule it to run daily at midnight
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Daily Log Cleanup",
"function_label": "daily_cleanup",
"cron_expression": "0 0 0 * * *",
"parameters": {"cutoff_date": "2026-01-01T00:00:00Z"},
"enabled": true,
"timezone": "UTC"
}'

Core Concepts

Cron Expressions

ekoDB uses 6-field cron expressions:

┌───────────── second (0-59)
│ ┌───────────── minute (0-59)
│ │ ┌───────────── hour (0-23)
│ │ │ ┌───────────── day of month (1-31)
│ │ │ │ ┌───────────── month (1-12 or JAN-DEC)
│ │ │ │ │ ┌───────────── day of week (0-6 or SUN-SAT)
│ │ │ │ │ │
* * * * * *

Common Schedules

ExpressionDescriptionRuns At
0 * * * * *Every minute:00 seconds of every minute
0 0 * * * *Every hourTop of every hour
0 0 0 * * *Daily at midnight00:00:00 every day
0 0 9 * * MON-FRIWeekdays at 9 AM9:00 AM Monday-Friday
0 0 0 1 * *Monthly on 1stMidnight on 1st of month
0 */15 * * * *Every 15 minutes:00, :15, :30, :45 of each hour
0 30 2 * * *Daily at 2:30 AM2:30 AM every day

Special Characters

  • * - Any value (every)
  • , - Value list separator (1,15,30)
  • - - Range (MON-FRI, 9-17)
  • / - Step values (*/15 = every 15 units)

Creating Schedules

Step 1: Create a Function

First, create the function you want to schedule:

curl -X POST https://{EKODB_API_URL}/api/functions \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"label": "generate_report",
"description": "Generate daily analytics report",
"functions": [
{
"type": "Aggregate",
"collection": "events",
"pipeline": [
{
"stage": "Filter",
"config": {
"field": "timestamp",
"operator": "GreaterThan",
"value": "{{start_date}}"
}
},
{
"stage": "Group",
"config": {
"by": ["event_type"],
"aggregations": [
{ "function": "Count", "output_field": "total" }
]
}
}
]
},
{
"type": "Insert",
"collection": "reports",
"record": {
"type": "daily_analytics",
"generated_at": "{{current_time}}",
"data": "{{previous_result}}"
}
}
]
}'

Step 2: Schedule the Function

curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Daily Analytics Report",
"description": "Generate analytics every day at 1 AM",
"function_label": "generate_report",
"cron_expression": "0 0 1 * * *",
"parameters": {
"start_date": "2026-01-01T00:00:00Z",
"current_time": "{{NOW}}"
},
"enabled": true,
"timezone": "America/New_York"
}'

# Response includes schedule id and next_execution timestamp

Managing Schedules

List All Schedules

curl -X GET https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}"

Get Schedule by ID

curl -X GET https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

Update Schedule

# Change schedule time
curl -X PUT https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"cron_expression": "0 0 2 * * *"
}'

# Update parameters
curl -X PUT https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"parameters": {
"start_date": "2026-06-01T00:00:00Z"
}
}'

Enable/Disable Schedule

# Disable temporarily
curl -X PUT https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{"enabled": false}'

# Re-enable
curl -X PUT https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{"enabled": true}'

Delete Schedule

curl -X DELETE https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

Execution & Monitoring

Execution Lifecycle

  1. Schedule Check (every 60 seconds)

    • ScheduleManager loads all enabled schedules
    • Calculates if next_execution <= now
  2. Function Execution

    • Calls the associated function with parameters
    • Measures execution time
    • Updates last_execution timestamp
  3. Statistics Update

    • Increments total_executions
    • Updates success/failure counts
    • Calculates average execution time
    • Logs errors if execution fails
  4. Next Execution Calculation

    • Determines next run based on cron expression
    • Updates next_execution field

Execution Statistics

curl -X GET https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

# Response includes stats object:
# {
# "stats": {
# "total_executions": 42,
# "successful_executions": 41,
# "failed_executions": 1,
# "avg_execution_time_ms": 125.3,
# "last_error": null
# }
# }

You can also retrieve aggregate stats across all schedules:

curl -X GET https://{EKODB_API_URL}/api/schedules/stats \
-H "Authorization: Bearer {TOKEN}"

Error Handling

When a scheduled function fails, check the schedule's stats.last_error field:

curl -X GET https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

# Check stats.failed_executions and stats.last_error in the response

Real-World Use Cases

Data Cleanup

# Remove old records daily at 3 AM
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Delete Old Logs",
"function_label": "cleanup_old_logs",
"cron_expression": "0 0 3 * * *",
"parameters": {"days_to_keep": 30},
"enabled": true
}'

Periodic Reports

# Generate weekly summary on Sundays at 9 AM
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Weekly Summary",
"function_label": "generate_weekly_summary",
"cron_expression": "0 0 9 * * SUN",
"parameters": {"email_to": "team@company.com"},
"enabled": true
}'

Data Synchronization

# Sync with external API every hour
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Sync External Data",
"function_label": "sync_external_api",
"cron_expression": "0 0 * * * *",
"parameters": {"api_endpoint": "https://api.example.com/data"},
"enabled": true
}'

Cache Warming

# Pre-load frequently accessed data every 30 minutes
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Warm Cache",
"function_label": "warm_product_cache",
"cron_expression": "0 */30 * * * *",
"parameters": {"top_n": 100},
"enabled": true
}'

Backup & Archival

# Archive old data on the 1st of each month
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Monthly Archive",
"function_label": "archive_old_data",
"cron_expression": "0 0 0 1 * *",
"parameters": {
"archive_collection": "archived_data",
"months_old": 6
},
"enabled": true
}'

Dynamic Parameters

Use dynamic values in your scheduled functions:

curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Daily Report",
"function_label": "generate_report",
"cron_expression": "0 0 1 * * *",
"parameters": {
"report_date": "{{NOW}}",
"start_date": "{{NOW-1d}}",
"end_date": "{{NOW}}",
"recipient": "reports@company.com"
},
"enabled": true
}'

Supported dynamic values:

  • {{NOW}} - Current timestamp
  • {{NOW-1d}} - 1 day ago
  • {{NOW-1h}} - 1 hour ago
  • {{NOW-1w}} - 1 week ago

Best Practices

1. Choose Appropriate Times

# ✅ Good - Run during low-traffic hours
"cron_expression": "0 0 3 * * *" # 3 AM

# ❌ Avoid - Peak business hours
"cron_expression": "0 0 12 * * *" # Noon

2. Set Realistic Intervals

# ✅ Good - Hourly for data sync
"cron_expression": "0 0 * * * *"

# ❌ Avoid - Every second (too frequent)
"cron_expression": "* * * * * *"

3. Monitor Execution Times

Retrieve a schedule and check stats.avg_execution_time_ms. If execution time is growing, consider optimizing the underlying function.

curl -X GET https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

# Check stats.avg_execution_time_ms in the response

4. Handle Failures Gracefully

Build error handling into your function definition:

curl -X POST https://{EKODB_API_URL}/api/functions \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"label": "safe_cleanup",
"functions": [
{
"type": "Delete",
"collection": "logs",
"filter": {
"field": "created_at",
"operator": "LessThan",
"value": "{{cutoff_date}}"
},
"error_handling": "continue"
}
]
}'

5. Use Timezone Awareness

# ✅ Good - Specify timezone for business hours
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "Business Hours Report",
"function_label": "report",
"cron_expression": "0 0 9 * * MON-FRI",
"timezone": "America/New_York",
"enabled": true
}'

6. Test Before Enabling

# 1. Create disabled, test manually first
curl -X POST https://{EKODB_API_URL}/api/schedules \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "New Schedule",
"function_label": "new_function",
"cron_expression": "0 0 * * * *",
"enabled": false
}'

# 2. Manually trigger the function to test
curl -X POST https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID}/trigger \
-H "Authorization: Bearer {TOKEN}"

# 3. Enable after verification
curl -X PUT https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{"enabled": true}'

Troubleshooting

Schedule Not Running

Problem: Schedule exists but function never executes

Solutions:

  1. Check enabled is true
  2. Verify cron expression is valid
  3. Check next_execution timestamp
  4. Ensure function exists with correct label
curl -X GET https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

# Verify enabled, next_execution, and function_label in the response

Function Fails

Problem: Schedule runs but function execution fails

Solutions:

  1. Check stats.last_error for error message
  2. Verify function parameters are correct
  3. Test function manually
  4. Check function permissions
curl -X GET https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}"

# Check stats.last_error and stats.failed_executions in the response

Timezone Issues

Problem: Schedule runs at wrong time

Solutions:

  1. Verify timezone is set correctly
  2. Use UTC for consistency
  3. Account for daylight saving time
curl -X PUT https://{EKODB_API_URL}/api/schedules/{SCHEDULE_ID} \
-H "Authorization: Bearer {TOKEN}" \
-H "Content-Type: application/json" \
-d '{"timezone": "UTC"}'

API Reference

Create Schedule

POST /api/schedules

Request body:

FieldTypeRequiredDescription
namestringYesDisplay name for the schedule
descriptionstringNoOptional description
function_labelstringYesLabel of the function to execute
cron_expressionstringYes6-field cron expression
parametersobjectNoParameters to pass to the function
enabledbooleanYesWhether the schedule is active
timezonestringNoTimezone (default: UTC)

List Schedules

GET /api/schedules

Get Schedule

GET /api/schedules/{id}

Update Schedule

PUT /api/schedules/{id}

Request body: Any subset of the fields from Create Schedule.

Delete Schedule

DELETE /api/schedules/{id}

Trigger Schedule

POST /api/schedules/{id}/trigger

Manually triggers immediate execution of a schedule, regardless of cron timing.

Schedule Stats

GET /api/schedules/stats

Returns aggregate statistics across all schedules.

Summary

Scheduled functions in ekoDB enable:

Automation - Recurring tasks without manual intervention ✅ Flexible scheduling - Cron-based with 6-field precision ✅ Background execution - Non-blocking operation ✅ Monitoring - Built-in execution statistics ✅ Error tracking - Automatic error logging ✅ Timezone support - Schedule across time zones ✅ Production-ready - Reliable and maintainable