Prompt
How do I use serverless for scheduled jobs and cron tasks?
Latest observation
You can use Serverless to run scheduled jobs by combining it with the cloud provider’s native scheduler.
The basic idea
Instead of running a server process continuously, you define a function that gets invoked on a schedule, such as:
- every minute
- every hour
- every day at midnight
- weekdays only
- a custom cron expression
Serverless frameworks then deploy that function and create the cloud scheduling rule for you.
Example: Serverless Framework + AWS
In serverless.yml:
service: scheduled-jobs
provider:
name: aws
runtime: nodejs20.x
functions:
cleanup:
handler: handler.cleanup
events:
- schedule: rate(5 minutes)
dailyReport:
handler: handler.dailyReport
events:
- schedule: cron(0 2 * * ? *)
Example handler
// handler.js
module.exports.cleanup = async () => {
console.log("Running cleanup job");
};
module.exports.dailyReport = async () => {
console.log("Generating daily report");
};
Cron syntax in AWS
AWS uses a cron format slightly different from standard cron:
cron(Minutes Hours Day-of-month Month Day-of-week Year)
Example:
cron(0 2 * * ? *)
Meaning:
- 0 minutes
- 2 AM UTC
- every day
- every month
- no specific day-of-week
- every year
Also note:
- AWS schedules are typically in UTC
?is used in either day-of-month or day-of-week to avoid ambiguity
Other providers
Google Cloud / Cloud Scheduler
You can trigger serverless functions with Cloud Scheduler and a pub/sub or HTTP trigger.
Azure Functions
Azure has built-in timer triggers:
{
"schedule": "0 */5 * * * *"
}
This example runs every 5 minutes.
Good use cases
Scheduled serverless jobs are great for:
- data cleanup
- sending digest emails
- generating reports
- syncing records
- polling external APIs
- cache warming
- backup jobs
Important considerations
1. Idempotency
Your job may run more than once, so make sure it can safely retry without causing problems.
2. Time zones
Most cloud schedulers use UTC by default. Convert carefully if you need local time.
3. Long-running jobs
Serverless functions have execution time limits. If the job might take too long, split it into chunks or offload work to a queue.
4. Reliability
If you need guaranteed execution, consider:
- retries
- dead-letter queues
- persistence/state tracking
- locking to prevent duplicate runs
If you want a cron-like setup locally
You can also test your jobs locally with:
serverless invoke local- a local scheduler like
node-cron - a mock event payload
But in production, use the cloud scheduler, not a process that must stay running.
If you want, I can show you:
- a full AWS Serverless Framework cron example,
- an Azure Functions timer trigger, or
- a Serverless Framework setup for multiple scheduled jobs.