Linux on Raspberry Pi
systemd services, cron jobs, logging, and running code at boot
Skills taught: embedded.rpi-linux
Running Scripts at Boot with systemd
systemd is the init system on Raspberry Pi OS. It starts and supervises all system processes. To run your Python script as a service, create a .service unit file and register it with systemd. This gives you automatic startup, crash recovery, and centralised logging.
[Unit]
Description=Sensor Data Logger
Documentation=https://github.com/yourname/sensor-logger
After=network.target # start after network is up
Wants=network.target
[Service]
Type=simple
User=pi
Group=pi
WorkingDirectory=/home/pi/sensor-logger
Environment=PYTHONUNBUFFERED=1
ExecStart=/home/pi/sensor-logger/venv/bin/python main.py
# Auto-restart on crash
Restart=always
RestartSec=5
StartLimitIntervalSec=0 # no limit on restart attempts
# Log to journal
StandardOutput=journal
StandardError=journal
SyslogIdentifier=sensor-logger
[Install]
WantedBy=multi-user.target
# 1. Copy service file
sudo cp sensor-logger.service /etc/systemd/system/
# 2. Reload systemd to pick up new file
sudo systemctl daemon-reload
# 3. Enable: start at every boot
sudo systemctl enable sensor-logger.service
# 4. Start now (without rebooting)
sudo systemctl start sensor-logger.service
# 5. Check status
sudo systemctl status sensor-logger.service
# 6. View live logs (Ctrl+C to stop)
journalctl -u sensor-logger.service -f
# 7. View last 50 lines
journalctl -u sensor-logger.service -n 50 --no-pager
# Common control commands:
# sudo systemctl stop sensor-logger # stop
# sudo systemctl restart sensor-logger # restart
# sudo systemctl disable sensor-logger # don't start at boot
Tip: Always use a Python virtual environment in your service: `ExecStart=/home/pi/myproject/venv/bin/python main.py`. This isolates dependencies and avoids conflicts between projects. Create the venv with `python3 -m venv venv` inside the project directory.
Scheduled Tasks with cron
cron runs commands on a time schedule. Use crontab -e to edit your user's cron table. Common patterns: hourly data upload, daily log rotation, weekly backups.
# Edit your user's cron jobs
crontab -e
# Crontab format:
# min hour day month weekday command
# * * * * *
# Example cron jobs:
# Run sensor upload every 5 minutes
*/5 * * * * /home/pi/scripts/upload_sensor.py >> /home/pi/logs/upload.log 2>&1
# Run backup every day at 2:30 AM
30 2 * * * /home/pi/scripts/backup.sh >> /home/pi/logs/backup.log 2>&1
# Reboot Pi every Monday at 4 AM (keep Pi fresh)
0 4 * * 1 /sbin/reboot
# Run on reboot
@reboot sleep 30 && /home/pi/scripts/startup.py >> /home/pi/logs/startup.log 2>&1
# View current cron jobs
crontab -l
Log Management with journalctl
All systemd services log to the journal automatically. journalctl is your primary debugging tool for deployed Pi projects. The journal survives service crashes and stores structured logs with timestamps.
# Live stream logs from your service
journalctl -u sensor-logger -f
# Last 100 lines
journalctl -u sensor-logger -n 100 --no-pager
# Logs since yesterday
journalctl -u sensor-logger --since yesterday
# Logs between specific times
journalctl -u sensor-logger --since "2026-11-14 09:00" --until "2026-11-14 10:00"
# Only errors
journalctl -u sensor-logger -p err
# System boot logs
journalctl -b # current boot
journalctl -b -1 # previous boot (useful after crash)
# Disk usage of journal
journalctl --disk-usage
# Limit journal size (edit /etc/systemd/journald.conf)
# SystemMaxUse=50M
File Permissions and Python Script Best Practices
# Make Python script executable
chmod +x /home/pi/myproject/main.py
# Add shebang line at top of main.py:
# #!/home/pi/myproject/venv/bin/python
# Fix file ownership
chown -R pi:pi /home/pi/myproject/
# Create log directory with correct permissions
mkdir -p /home/pi/logs
chown pi:pi /home/pi/logs
# Test run as the pi user (before systemd)
sudo -u pi /home/pi/myproject/venv/bin/python /home/pi/myproject/main.py
# Check what a running service is doing
sudo lsof -p $(systemctl show -p MainPID sensor-logger | cut -d= -f2)
systemd Service vs cron for Automation
- systemd Service: Long-running daemon managed by systemd
- cron Job: Scheduled one-shot command execution
Warning: When a systemd service needs to access GPIO, it must run as the `pi` user (or add the user to the `gpio` group) — running as root is unnecessary and a security risk. Add `User=pi` and `Group=pi` to your .service file, and ensure the user is in the `gpio` and `i2c` groups: `sudo usermod -aG gpio,i2c,spi pi`.
Frequently Asked Questions
How do I schedule a script to run every 5 minutes?
Edit crontab with `crontab -e` and add: `*/5 * * * * /home/pi/venv/bin/python /home/pi/script.py >> /home/pi/logs/script.log 2>&1`. The 2>&1 redirects stderr to the same log file so you capture errors.
My service starts but then stops immediately. How do I diagnose it?
Run `journalctl -u yourservice -n 50 --no-pager` to see the last 50 log lines including any Python tracebacks. Also run the ExecStart command manually from the terminal as the same user (e.g., `sudo -u pi /path/to/venv/bin/python main.py`) to see errors directly.
Can a systemd service start before WiFi is connected?
Yes, unless you tell it not to. Add `After=network-online.target` and `Wants=network-online.target` (instead of just network.target) to wait until the network interface has an IP address before starting. Also enable the network-online service: `sudo systemctl enable systemd-networkd-wait-online`.