0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use Cron Jobs on Raspberry Pi: Simple Guide

On Raspberry Pi, use cron to schedule tasks by editing the crontab with crontab -e. Write commands with timing syntax to run scripts or commands automatically at set intervals.
📐

Syntax

The cron job syntax has five time fields followed by the command to run:

  • Minute (0-59)
  • Hour (0-23)
  • Day of Month (1-31)
  • Month (1-12)
  • Day of Week (0-6, Sunday=0 or 7)

Each field can be a number, a range, a list, or an asterisk (*) meaning 'every'. After these fields, write the command or script path to execute.

bash
* * * * * /path/to/command_or_script
💻

Example

This example runs a Python script every day at 7:30 AM. It shows how to edit the crontab and add the job.

bash
# Open crontab editor
crontab -e

# Add this line to run script at 7:30 AM daily
30 7 * * * /usr/bin/python3 /home/pi/myscript.py

# Save and exit the editor
Output
Cron job added: runs /home/pi/myscript.py daily at 7:30 AM
⚠️

Common Pitfalls

Common mistakes include:

  • Not using full paths for commands or scripts, causing cron to fail.
  • Forgetting to make scripts executable with chmod +x.
  • Not redirecting output, so errors are hidden.
  • Editing the wrong user's crontab or not saving changes.

Always test your commands manually before scheduling.

bash
# Wrong: relative path and no output redirection
* * * * * python3 myscript.py

# Right: full path and output logged
* * * * * /usr/bin/python3 /home/pi/myscript.py >> /home/pi/myscript.log 2>&1
📊

Quick Reference

Tips for using cron on Raspberry Pi:

  • Use crontab -e to edit your cron jobs.
  • Use full paths for commands and scripts.
  • Redirect output to log files for debugging.
  • Check cron logs with grep CRON /var/log/syslog.
  • Restart cron service if needed: sudo systemctl restart cron.

Key Takeaways

Use crontab -e to schedule tasks on Raspberry Pi with cron syntax.
Always specify full paths for commands and scripts in cron jobs.
Redirect output to log files to catch errors and debug.
Make scripts executable and test commands manually before scheduling.
Check cron logs and restart the cron service if jobs don't run.