0
0
Raspberry Piprogramming~5 mins

Scheduled data collection with cron in Raspberry Pi

Choose your learning style9 modes available
Introduction
Scheduling data collection helps you automatically gather information at set times without doing it manually.
You want to record temperature every hour from a sensor.
You need to save system performance data daily.
You want to back up your database every night.
You want to collect data from a website every 10 minutes.
You want to run a script to clean old data weekly.
Syntax
Raspberry Pi
crontab -e

# Each line in crontab has this format:
# * * * * * command_to_run
# | | | | |
# | | | | +---- Day of week (0-7, Sunday=0 or 7)
# | | | +------ Month (1-12)
# | | +-------- Day of month (1-31)
# | +---------- Hour (0-23)
# +------------ Minute (0-59)
Use 'crontab -e' to edit your scheduled tasks.
The five stars (*) mean 'every' unit of time (every minute, hour, etc.).
Examples
Runs the script 'collect_data.sh' every hour at minute 0.
Raspberry Pi
0 * * * * /home/pi/collect_data.sh
Runs the script every 10 minutes.
Raspberry Pi
*/10 * * * * /home/pi/collect_data.sh
Runs the backup script every Sunday at midnight.
Raspberry Pi
0 0 * * 0 /home/pi/backup_db.sh
Sample Program
This example sets up a script that records the Raspberry Pi's CPU temperature every 15 minutes into a text file.
Raspberry Pi
# Step 1: Create a script to collect data
# File: /home/pi/collect_data.sh
#!/bin/bash
DATE=$(date '+%Y-%m-%d %H:%M:%S')
TEMP=$(vcgencmd measure_temp | egrep -o '[0-9]*\.[0-9]*')
echo "$DATE Temperature: $TEMP C" >> /home/pi/temperature_log.txt

# Step 2: Make the script executable
# Run in terminal:
chmod +x /home/pi/collect_data.sh

# Step 3: Schedule the script to run every 15 minutes
# Run in terminal:
crontab -e
# Add this line:
*/15 * * * * /home/pi/collect_data.sh
OutputSuccess
Important Notes
Make sure your script has execute permission (chmod +x).
Cron runs commands with limited environment; use full paths in scripts.
Check cron logs if your scheduled task does not run as expected.
Summary
Cron helps automate tasks by running scripts at set times.
Use 'crontab -e' to add or edit scheduled jobs.
Scripts must be executable and use full paths for reliability.