Skip to Content
Serverless Tasks

Serverless Tasks - Complete Guide

Run scheduled tasks and cron jobs with support for Bash, Python, Go, and Bun. Perfect for automation, data processing, and maintenance tasks.

Overview

Serverless Tasks allow you to run code on a schedule without managing servers. Use them for periodic jobs like data backups, report generation, API syncing, cleanup tasks, and more.

Access Path: /dashboard/compute/serverless/tasks


Viewing Your Tasks

Tasks List Page

When you navigate to /dashboard/compute/serverless/tasks, you’ll see:

Search & Filter

  • Search box at the top - Search by task name
  • Results filter as you type

Task Cards

Each task displays as a card showing:

  • Task Name - The identifier you assigned
  • Schedule - Cron expression (e.g., */5 * * * * = every 5 minutes)
  • Status Badge - Current state:
    • 🟢 Running - Task is scheduled and executing
    • 🟡 Pending - Task is being created
    • 🔴 Failed - Last execution failed
    • Stopped - Task is paused/disabled
  • Language - Runtime (Bash, Python, Go, Bun)
  • Last Run - When the task last executed
  • Next Run - When the task will execute next

Actions

  • New Task button (top right) - Create a new scheduled task
  • Click any card - Open the task details page

Use descriptive names for tasks to easily identify their purpose (e.g., daily-backup, hourly-sync, weekly-report).


Creating a New Task

Click New Task to start the creation wizard.

Step 1: Task Name

Task Name

  • Enter a unique identifier for your task
  • Use lowercase letters, numbers, and hyphens
  • Example: daily-backup, send-reports, cleanup-old-files
  • This name appears in logs and notifications

Naming Best Practices

  • Include frequency hint (daily, hourly, weekly)
  • Describe the action (backup, sync, cleanup)
  • Keep it short but meaningful

Step 2: Schedule Configuration

Cron Expression

  • Define when your task runs using cron syntax
  • Default: * * * * * (every minute)

Common Cron Patterns

ExpressionDescription
* * * * *Every minute
*/5 * * * *Every 5 minutes
0 * * * *Every hour (at minute 0)
0 0 * * *Daily at midnight
0 9 * * *Daily at 9:00 AM
0 0 * * 0Weekly on Sunday at midnight
0 0 1 * *Monthly on the 1st at midnight
0 9 * * 1-5Weekdays at 9:00 AM

Cron Format

* * * * * │ │ │ │ │ │ │ │ │ └─ Day of week (0-7, 0 and 7 = Sunday) │ │ │ └─── Month (1-12) │ │ └───── Day of month (1-31) │ └─────── Hour (0-23) └───────── Minute (0-59)

Timezone

  • Select your timezone from the dropdown
  • Default: UTC
  • Common options: America/New_York, Europe/London, Asia/Tokyo
  • Task executes according to this timezone

Be careful with very frequent schedules (every minute). They can consume resources quickly and increase costs.

Step 3: Execution Settings

Timeout

  • Maximum execution time in seconds
  • Default: 300 (5 minutes)
  • Range: 10 - 3600 seconds (10 seconds to 1 hour)
  • Task is terminated if it exceeds this time

Timeout Recommendations

  • Quick scripts: 30-60 seconds
  • API calls: 60-300 seconds
  • Data processing: 300-1800 seconds
  • Heavy operations: 1800-3600 seconds

Step 4: Language & Script

Select Language

Choose your runtime:

Bash

  • Shell scripting
  • System commands
  • File operations
  • Good for: Simple automation, file management

Python

  • Python 3.x
  • Rich library ecosystem
  • Data processing
  • Good for: API calls, data analysis, web scraping

Go

  • Compiled Go programs
  • High performance
  • Concurrent operations
  • Good for: Fast processing, system tasks

Bun

  • JavaScript/TypeScript runtime
  • Fast execution
  • Modern syntax
  • Good for: Node.js-style scripts, API integrations

Script Editor

  • Write your code in the text area
  • Syntax highlighting provided
  • Multi-line support
  • No file upload needed

Example Scripts

Bash Example

#!/bin/bash echo "Starting backup..." date # Your backup logic here curl -X POST https://api.example.com/backup echo "Backup completed"

Python Example

import requests from datetime import datetime print(f"Task started at {datetime.now()}") # Make API call response = requests.get('https://api.example.com/data') print(f"Status: {response.status_code}") # Process data data = response.json() print(f"Processed {len(data)} items")

Bun Example

console.log('Task started:', new Date().toISOString()); // Fetch data const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(`Processed ${data.length} items`);

Step 5: Pricing Plan

Choose resources for your task:

Plan Options

Micro - 0.25 vCPU, 256 MB RAM

  • Very light tasks
  • Simple scripts
  • Quick operations

Small - 0.5 vCPU, 512 MB RAM

  • Light processing
  • API calls
  • File operations

Medium - 1 vCPU, 1 GB RAM

  • Data processing
  • Multiple API calls
  • Moderate workloads

Large - 2 vCPU, 2 GB RAM

  • Heavy processing
  • Large datasets
  • Complex operations

Billing

  • Charged per execution
  • Based on execution time
  • Rounded to nearest second

Step 6: Environment Variables

Add environment variables your script needs:

Adding Variables

  • Click Add Variable to create a new row
  • Enter Name (e.g., API_KEY, DATABASE_URL)
  • Enter Value (the secret or configuration)
  • Click Add Variable again for more

Common Variables

  • API_KEY=your-secret-key
  • DATABASE_URL=postgresql://...
  • WEBHOOK_URL=https://...
  • [email protected]

Accessing in Scripts

Bash

echo "API Key: $API_KEY" curl -H "Authorization: Bearer $API_KEY" https://api.example.com

Python

import os api_key = os.environ['API_KEY']

Bun/JavaScript

const apiKey = process.env.API_KEY;

Environment variables are encrypted at rest. Never commit secrets to version control.

Step 7: Create Task

Click Create Task to schedule your task.

What Happens Next

  1. Task is validated and created
  2. Schedule is activated
  3. First execution happens at next scheduled time
  4. You’re redirected to task list

Managing Your Task

Click on any task card to open the task details page.

Task Details Header

Task Name & Status

  • Large task name at the top
  • Status badge showing current state
  • Last execution timestamp

Primary Actions

  • Update Scheduled Task - Modify task configuration
  • Delete Scheduled Task - Remove the task permanently

Task Details View

Task Information

Name

  • Your task identifier
  • Displayed prominently

Status

  • Current operational state
  • Running, Stopped, Failed, or Pending

Schedule

  • Cron Expression: The schedule pattern
  • Timezone: Execution timezone
  • Next Run: When task will execute next

Configuration

  • Timeout: Maximum execution time
  • Language: Runtime environment
  • Created: When task was created

Resources

  • Plan: Current pricing tier
  • vCPU: Allocated CPU
  • RAM: Memory allocation

Script

  • View your task’s code
  • Syntax-highlighted display
  • Read-only in details view

Environment Variables

  • List of configured variables
  • Values are masked by default
  • Click eye icon to reveal

Updating a Task

Click Update Scheduled Task to modify your task.

Editable Fields

Task Name

  • Change the display name
  • Must remain unique

Schedule

  • Modify cron expression
  • Change timezone
  • Update execution frequency

Timeout

  • Adjust maximum execution time
  • Based on your needs

Script

  • Edit your code
  • Change logic
  • Fix bugs

Language

  • Switch runtime if needed
  • Requires script rewrite

Environment Variables

  • Add new variables
  • Update existing values
  • Remove unused variables

Plan

  • Upgrade or downgrade resources
  • Based on task requirements

Saving Changes

Click Save Changes to apply modifications.

Important Notes

  • Changes take effect immediately
  • Next execution uses new configuration
  • Running executions continue with old config
  • No downtime during updates

Execution History

Viewing Logs

Execution List

  • Shows recent task runs
  • Displays execution time
  • Shows success/failure status
  • Includes duration

Log Details

  • Click on an execution to view logs
  • See console output
  • Check error messages
  • Review execution time

Log Retention

  • Logs kept for 7 days
  • Download important logs
  • Use for debugging

Common Workflows

Daily Backup Task

Create Backup Task

  1. Click New Task
  2. Name: daily-database-backup
  3. Schedule: 0 2 * * * (2 AM daily)
  4. Timezone: Your timezone
  5. Timeout: 600 seconds

Write Backup Script

Python Example

import os import subprocess from datetime import datetime # Get credentials from environment db_url = os.environ['DATABASE_URL'] backup_bucket = os.environ['BACKUP_BUCKET'] # Create backup filename date_str = datetime.now().strftime('%Y%m%d') backup_file = f'backup-{date_str}.sql' # Run backup print(f'Starting backup: {backup_file}') subprocess.run(['pg_dump', db_url, '-f', backup_file]) # Upload to storage print('Uploading to cloud storage...') # Your upload logic here print('Backup completed successfully')

Add Environment Variables

  • DATABASE_URL: Your database connection string
  • BACKUP_BUCKET: Storage location

Test & Monitor

  1. Save the task
  2. Manually trigger first run (if possible)
  3. Check logs for success
  4. Monitor daily executions

API Data Sync

Create Sync Task

  1. Name: hourly-api-sync
  2. Schedule: 0 * * * * (every hour)
  3. Language: Bun/JavaScript
  4. Timeout: 300 seconds

Write Sync Script

const API_KEY = process.env.API_KEY; const WEBHOOK_URL = process.env.WEBHOOK_URL; console.log('Starting sync:', new Date().toISOString()); // Fetch data from source const response = await fetch('https://api.source.com/data', { headers: { 'Authorization': `Bearer ${API_KEY}` } }); const data = await response.json(); console.log(`Fetched ${data.length} records`); // Send to destination await fetch(WEBHOOK_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); console.log('Sync completed');

Configure Variables

  • API_KEY: Source API key
  • WEBHOOK_URL: Destination endpoint

Monitor

Check logs after each execution to ensure sync is working.

Cleanup Old Files

Create Cleanup Task

  1. Name: weekly-cleanup
  2. Schedule: 0 3 * * 0 (Sunday 3 AM)
  3. Language: Bash
  4. Timeout: 180 seconds

Write Cleanup Script

#!/bin/bash echo "Starting cleanup: $(date)" # Delete files older than 30 days find /tmp/uploads -type f -mtime +30 -delete # Clean up logs find /var/log/app -name "*.log" -mtime +7 -delete # Report results echo "Cleanup completed: $(date)" echo "Disk usage:" df -h

Schedule & Monitor

Task runs weekly and keeps your system clean.


Best Practices

Scheduling

  • ✅ Use appropriate frequencies (don’t over-schedule)
  • ✅ Consider timezone for business hours tasks
  • ✅ Avoid scheduling many tasks at the same time
  • ✅ Use off-peak hours for heavy operations
  • ✅ Test cron expressions before deploying

Script Development

  • ✅ Test scripts locally first
  • ✅ Add error handling
  • ✅ Include logging statements
  • ✅ Set appropriate timeouts
  • ✅ Handle edge cases

Error Handling

  • ✅ Use try-catch blocks
  • ✅ Log errors clearly
  • ✅ Set up notifications for failures
  • ✅ Include retry logic for transient errors
  • ✅ Exit with proper status codes

Security

  • ✅ Use environment variables for secrets
  • ✅ Never hardcode credentials
  • ✅ Limit task permissions
  • ✅ Validate external inputs
  • ✅ Use HTTPS for API calls

Monitoring

  • ✅ Check logs regularly
  • ✅ Monitor execution times
  • ✅ Track success/failure rates
  • ✅ Set up alerts for critical tasks
  • ✅ Review resource usage

Troubleshooting

Task Not Executing

Symptoms: Task status is “Running” but no executions appear

Solutions:

  1. Verify cron expression is correct
  2. Check if next run time has passed
  3. Ensure task isn’t paused
  4. Review timezone settings
  5. Check for system-wide issues

Task Timing Out

Symptoms: Executions fail with timeout error

Solutions:

  1. Increase timeout value
  2. Optimize script performance
  3. Upgrade to larger plan
  4. Break task into smaller chunks
  5. Remove unnecessary operations

Script Errors

Symptoms: Task fails with error in logs

Solutions:

  1. Review error message in logs
  2. Test script locally
  3. Check environment variables are set
  4. Verify external services are accessible
  5. Add error handling to script

Environment Variables Not Working

Symptoms: Script can’t access variables

Solutions:

  1. Verify variables are saved
  2. Check variable names match exactly (case-sensitive)
  3. Ensure no typos in variable names
  4. Test with simple echo/print statements
  5. Restart task after adding variables

High Resource Usage

Symptoms: Task uses too much CPU/memory

Solutions:

  1. Optimize script code
  2. Reduce data processing volume
  3. Upgrade to larger plan
  4. Split into multiple smaller tasks
  5. Add resource limits in code

Cron Expression Helper

Building Cron Expressions

Every Minute

* * * * *

Every 15 Minutes

*/15 * * * *

Every Hour at 30 Minutes Past

30 * * * *

Every Day at Specific Time

0 14 * * * # 2:00 PM daily

Weekdays Only

0 9 * * 1-5 # 9 AM Monday-Friday

Specific Days

0 0 * * 0,3 # Midnight on Sunday and Wednesday

First Day of Month

0 0 1 * * # Midnight on the 1st

Multiple Times Per Day

0 9,12,15,18 * * * # 9 AM, 12 PM, 3 PM, 6 PM

Testing Cron Expressions

Use online tools:


Next Steps

Need help with cron expressions or script debugging? Contact our support team with your task ID.