15% off your workspace - subscribe to our blogNo per-service fees - one plan, unlimited appsDeploy in under 40 seconds99.95% uptime SLAFree tier available - start building today15% off your workspace - subscribe to our blogNo per-service fees - one plan, unlimited appsDeploy in under 40 seconds99.95% uptime SLAFree tier available - start building today
Miget x AIPlansEnterpriseCompareBlogDashboard
Start for Free
Blog/Tutorial/Deployment/
·

How to Run Cron Jobs on a Modern PaaS

Many web applications need to run tasks on a recurring schedule-sending email reports, cleaning up old data, or syncing with an external API. These scheduled tasks, often called cron jobs, are a fundamental part of backend automation. While setting them up on a traditional server involves editing system files, a modern PaaS makes the process much simpler and more reliable.

This guide explains what cron jobs are, how they work on a Platform-as-a-Service, and how you can use them to automate critical parts of your application.

What is a Cron Job?

A cron job is a time-based scheduler in Unix-like operating systems. You define a command and a schedule, and the system executes the command automatically at the specified time. The schedule is defined using a compact syntax called a cron expression.

A cron expression has five fields, representing minute, hour, day of the month, month, and day of the week.

Here’s a breakdown of the syntax:

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

An asterisk (*) acts as a wildcard, meaning "every". For example, * * * * * means "every minute of every hour of every day".

Common Cron Schedule Examples

Here are a few practical examples to help you understand the syntax:

ScheduleExpressionDescription
Every Minute* * * * *Runs at the beginning of every minute.
Every 15 Minutes*/15 * * * *Runs at :00, :15, :30, and :45 past the hour.
Once an Hour0 * * * *Runs at the beginning of every hour.
Once a Day0 0 * * *Runs once a day at midnight.
Twice a Day0 0,12 * * *Runs at midnight and noon.
Weekdays at 5 PM0 17 * * 1-5Runs at 5:00 PM from Monday to Friday.
First of Month0 0 1 * *Runs at midnight on the first day of the month.

Understanding this syntax is the first step to automating your application's background jobs.

Common Use Cases for Scheduled Tasks

Cron jobs are versatile and can handle a wide range of automated tasks. Most production applications rely on them for routine maintenance and functionality.

  • Data Cleanup: Automatically delete soft-deleted records, expired user sessions, or temporary files from your database or object storage.
  • Reporting: Generate and email daily, weekly, or monthly analytics reports to your team or customers.
  • Data Synchronization: Periodically pull data from a third-party API to keep your application's database up to date.
  • Notifications: Send daily email digests, push notifications for expiring subscriptions, or other scheduled reminders.
  • Cache Warming: Pre-populate caches with frequently accessed data during off-peak hours to improve performance.
  • Backups: Trigger a script that creates a backup of application data and stores it in a secure location.

By automating these tasks, you reduce manual work and ensure your application runs smoothly.

How Cron Jobs Work on a PaaS

On a traditional server, you would typically SSH into the machine and edit a file called a crontab to add or remove cron jobs. This approach works, but it has several drawbacks: it's manual, not version-controlled, and doesn't scale easily.

Modern PaaS environments handle scheduled tasks differently. Instead of running on a shared, persistent server, a cron job on a PaaS runs as a one-off task using your application's container image.

This has several key advantages:

  1. Consistent Environment: The job runs with the exact same code, dependencies, and environment variables as your main web application. No more environment drift.
  2. Version Controlled: The command for your job is part of your application's codebase or PaaS configuration, so it can be tracked in Git.
  3. No Server Management: The platform is responsible for spinning up the container, running your command, and then tearing it down. You don't manage any infrastructure.
  4. Centralized Logging: The output (stdout and stderr) of your job is automatically collected and made available in your application's log stream, making debugging much easier.

How Miget Manages Cron Jobs

At Miget, cron jobs are a built-in feature of our application platform. You can schedule any command to run against your application's deployed image without provisioning a separate worker or paying for another service. It's all included in your Resource plan. Stop paying per app. Start paying per compute.

Let's walk through setting up a cron job on Miget. Imagine you have a Node.js application with a script to clean up inactive user accounts.

First, define the script in your project.

Here is a simple script named scripts/cleanup.js:

// scripts/cleanup.js
async function cleanupInactiveUsers() {
  console.log('Starting inactive user cleanup job...');
  // Your database logic goes here
  // Example: db.users.deleteMany({ lastLogin: { $lt: thirtyDaysAgo } });
  console.log('Cleanup job finished successfully.');
}

cleanupInactiveUsers();

Next, add a command for it in your package.json:

{
  "name": "my-app",
  "scripts": {
    "start": "node index.js",
    "cleanup": "node scripts/cleanup.js"
  }
}

With this setup, the command to run your cleanup task is npm run cleanup.

To schedule this on Miget, you navigate to your app's dashboard, go to the "Cronjobs" tab, and create a new one with the following configuration:

  • Label: Daily User Cleanup
  • Schedule: 0 3 * * * (Run every day at 3:00 AM)
  • Command: npm run cleanup

That's it. Miget's scheduler will now automatically create a new instance of your app's container, execute npm run cleanup, and stream the logs to your dashboard every day at 3 AM. Because the cron job runs in the same environment as your app, it automatically has access to all your environment variables, including DATABASE_URL, so it can connect to your database without any extra configuration.

Best Practices for Writing Cron Jobs

To ensure your scheduled tasks are reliable and maintainable, follow these best practices.

Make Jobs Idempotent

An idempotent operation is one that can be performed multiple times without changing the result beyond the initial application. If your job to delete inactive users runs twice by mistake, it shouldn't cause an error on the second run.

Implement Robust Logging

Your script should log its progress, including start time, end time, and any important outcomes. On a PaaS like Miget, this output is your primary tool for debugging a job that fails or behaves unexpectedly.

Handle Errors Gracefully

What happens if your job fails? It shouldn't crash or leave the system in a broken state. Wrap your logic in try...catch blocks and log any errors that occur. Consider integrating an alerting service to notify you of repeated failures.

Be Mindful of Resources

A cron job that consumes a lot of CPU or RAM can impact your main application's performance if they share resources. Schedule resource-intensive jobs for off-peak hours when traffic is low.

Frequently Asked Questions

What is the difference between a cron job and a worker?

A cron job is a task that runs on a schedule, executes, and then terminates. A worker is a long-running process that continuously consumes tasks from a queue. Cron jobs are for time-based triggers, while workers are for event-based or on-demand background processing.

How do I debug a failed cron job?

Check the logs. A PaaS will capture all output from your script. The logs will show you the exact error message, stack trace, and any custom log statements you added, which should be enough to identify the problem.

Can a cron job run longer than its interval?

Yes, and this can cause problems. For example, if a job takes 10 minutes to run but is scheduled to run every 5 minutes, you will end up with overlapping executions. Design your jobs to be fast, or implement a locking mechanism to prevent overlaps. For very long tasks, it's better to have the cron job simply enqueue a task for a dedicated background worker to process.

Next Steps

Automating routine tasks with cron jobs is a powerful way to make your application more robust and reduce manual overhead. Modern PaaS solutions like Miget integrate this functionality directly into your deployment workflow, providing a simple and reliable way to manage scheduled jobs without the complexity of traditional server administration.


How to Run Cron Jobs on a Modern PaaS - Miget Blog | Miget