How to run your script on a schedule using crontab on macOS: A step-by-step guide
Automate your shell, Node, Python, and Deno scripts with ease on macOS.
Introduction
Have you ever wanted to automate a task on your Mac, like backing up files, generating reports, or sending emails? These tasks can be repetitive and time-consuming, but with the help of crontab, you can schedule them to run at specific times, leaving you free to focus on more important things. In this article, we’ll explore the crontab tool and demonstrate how to use it to schedule scripts written in shell, Node, Python, and Deno.
How Crontab Works on Mac
Crontab is a Unix-based tool for managing and automating tasks on macOS. It uses a configuration file called the “crontab file” to store the scheduled jobs, also known as cron jobs. Each line in the crontab file represents a single cron job, consisting of a cron expression followed by the command to be executed.
A typical crontab file might look like this:
# Backup script daily at 3 AM
0 3 * * * /path/to/backup.sh
# Run a Node.js script every hour
0 * * * * /usr/local/bin/node /path/to/script.js
# Run a Python script every Monday at 4 PM
0 16 * * 1 /usr/bin/python3 /path/to/script.pyComments can be added by starting a line with the # symbol.
How to Use Crontab to Run Jobs on a Schedule
Editing Crontab with the Default Text Editor
To access and edit the crontab file on macOS, open Terminal and type the following command:
crontab -eThis will open your crontab file in your default text editor, which is usually Vim. You can add, modify, or remove cron jobs from this file. Save and exit the editor to apply your changes.
Editing Crontab with a Visual Text Editor
If you prefer using a visual text editor like Visual Studio Code, Sublime Text, or Atom, you can set the VISUAL environment variable to specify your preferred editor. For example, to use Visual Studio Code, run the following command in Terminal:
export VISUAL="code --wait"Then run crontab -e, and the crontab file will open in Visual Studio Code. Make your changes and save the file, then close the editor to apply the changes.
To make this change permanent, add the export VISUAL command to your shell's configuration file (e.g., ~/.bashrc, ~/.bash_profile, or ~/.zshrc).
Cron Expressions 101
A cron expression is a string of five fields separated by spaces. Each field represents a unit of time:
* * * * *
│ │ │ │ └───── day of the week (0 - 7, both 0 and 7 represent Sunday)
│ │ │ └─────── month (1 - 12)
│ │ └───────── day of the month (1 - 31)
│ └──────────── hour (0 - 23)
└─────────────── minute (0 - 59)Asterisks (*) are used as wildcards, meaning “any value.” You can also use comma-separated values, ranges, and increments (using the / symbol).
Using Commas to Specify Multiple Values
To run a job at 1:30 PM and 6:30 PM:
30 13,18 * * * your-commandUsing Ranges to Specify Value Ranges
To run a job every 30 minutes between 9 AM and 5 PM:
*/30 9-17 * * * your-commandUsing Increments to Specify Intervals
To run a job every 2 hours:
0 */2 * * * your-commandMost Common Cron Expressions for macOS
Execute a Job Once a Day at a Specified Time
To run a job at 2:30 AM daily:
30 2 * * * your-commandExecute a Job Every Hour
To run a job at the beginning of every hour:
0 * * * * your-commandExecute a Job Every Week on a Specified Day and Time
To run a job every Wednesday at 3:45 PM:
45 15 * * 3 your-commandExecute a Job Every Month on a Specified Day and Time
To run a job on the 15th of each month at 1 PM:
0 13 15 * * your-commandStep-by-Step Guide to Schedule a Job
Example for Shell Script
- Create a shell script file called “backup.sh” and make it executable:
#!/bin/bash
# Backup command2. Schedule the script to run daily at 3 AM:
0 3 * * * /path/to/backup.shExample for Node.js Script
- Create a Node.js script file called “email.js”:
const nodemailer = require('nodemailer');
// Your email sending logic2. Schedule the script to run every hour:
0 * * * * /usr/local/bin/node /path/to/email.jsExample for Deno Script
- Create a Deno script file called “report.ts”:
import { generateReport } from './reportGenerator.ts';
// Generate report and save it to a file2. Schedule the script to run every Tuesday at 8 PM:
0 20 * * 2 /usr/local/bin/deno run --allow-read --allow-write /path/to/report.tsExample for Python Script
- Create a Python script file called “analytics.py”:
import pandas as pd
# Your data analysis and visualization logic2. Schedule the script to run every Friday at 12 PM:
0 12 * * 5 /usr/bin/python3 /path/to/analytics.pyTools to Create Cron Expressions
There are several websites and apps that can help you create cron expressions for macOS, including:
These tools allow you to specify the desired schedule and provide you with the corresponding cron expression, making it easy to create and test your cron jobs.
Monitoring and Logging Scheduled Jobs with Crontab
In order to effectively manage your scheduled tasks, it’s important to know how to check which jobs are currently scheduled and how to view logs of past runs. This section will guide you through these essential monitoring and logging tasks.
Checking Scheduled Jobs
To view your current list of scheduled jobs, open Terminal and type the following command:
crontab -lThis command will display your current crontab file, showing all the scheduled cron jobs. Each line represents a single cron job, consisting of a cron expression followed by the command to be executed.
Viewing Logs of Past Runs
By default, macOS does not store detailed logs of cron jobs. However, you can redirect the output of your cron jobs to log files to keep track of their execution. To do this, modify your crontab file by adding output redirection to each cron job.
For example, to log the output of a shell script running daily at 3 AM, update the crontab entry like this:
0 3 * * * /path/to/backup.sh >> /path/to/backup.log 2>&1The >> operator appends the output to the specified log file, while 2>&1 ensures that both standard output (stdout) and standard error (stderr) are captured.
Once your cron jobs are set up to log their output, you can check these log files to see the results and any error messages generated by the jobs.
Alternatively, you can check the system log for basic information about the execution of cron jobs. To do this, open Terminal and type the following command:
grep -i cron /var/log/system.logThis command will display all log entries related to cron jobs, providing you with timestamps and basic information about the execution of your scheduled tasks.
