cron - macOS


Overview

cron is a time-based job scheduler in Unix-like operating systems including macOS. Users can schedule scripts or commands to run automatically at specified dates and times. Typical uses of cron include automating system maintenance and administration tasks, running regular backups, and monitoring systems with scheduled checks.

Syntax

The basic syntax for viewing, editing, or replacing the crontab (cron table) file is:

crontab [option] [file]

To edit or set up your cron jobs, you can specify the -e option, and to list your current cron jobs, you can use the -l option. To remove all your cron jobs, use the -r option.

Options/Flags

  • -l: Lists the current crontab entries for the invoking user.
  • -e: Edits the current crontab using the editor specified in the EDITOR environment variable or the default system editor.
  • -r: Deletes the current crontab.
  • -i: Provides a prompt before deleting the user’s crontab when used with the -r option.
  • -u user: Used with other options, this specifies the crontab to be listed, edited, or deleted belongs to the given user; this option is typically available to system administrators.

Examples

  1. Listing Cron Jobs
    View current cron jobs for the logged-in user:

    crontab -l
    
  2. Editing Cron Jobs
    Open the cron table for the current user in the default editor:

    crontab -e
    
  3. Setting a New Cron Job
    To run a script every day at 5 am:

    0 5 * * * /path/to/script.sh
    
  4. Deleting Cron Jobs
    To delete all cron jobs for the current user:

    crontab -r
    

Common Issues

  • Permission Errors: Users might encounter permission issues when trying to set cron jobs for other users. Ensure you have the appropriate permissions or run it as a superuser if necessary.
  • Environment Issues: Since cron jobs run in a minimal environment, certain environment variables needed by scripts might not be available. Ensure to define necessary environment variables inside the crontab or the scripts themselves.

Integration

cron can be used in conjunction with shell scripts to automate backups. For example, a simple backup script could be scheduled as follows:

Backup Script (backup.sh):

#!/bin/bash
tar -czf /backup/my_backup_$(date +"%Y%m%d_%H%M%S").tar.gz /data

Cron Jobs:
Schedule the backup to run every night at midnight:

0 0 * * * /path/to/backup.sh
  • at: Execute commands at a specified time.
  • launchd: Preferred over cron for scheduling jobs on macOS, managing system and application services.
  • anacron: Executes commands periodically, with a frequency defined in days.

For official documentation, users can explore the man pages on their system by executing man cron or visiting the official macOS developer documentation.