If you’re running automated backups on a laptop, traditional schedulers like cron or fcron might not be ideal. Your machine isn’t always on, and you might want to trigger backups specifically when the system starts up or wakes from sleep.

Here’s how to use systemd to run your backup script at these key moments.

The systemd Service File

Create /etc/systemd/system/backup.service:

[Unit]
Description=Run backup script at boot and wake-up
After=multi-user.target suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target

[Service]
Type=oneshot
User=yourusername
Group=yourgroup
ExecStart=/path/to/backup-script.sh

[Install]
WantedBy=multi-user.target suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target

The User and Group directives ensure the script runs as your user instead of root. This is important for:

  • Security (principle of least privilege)
  • Access to your user’s SSH keys and config files
  • Correct file permissions in backup destinations

Enable the Service

sudo systemctl enable backup.service

Your backup script will now run:

  • When the system boots up (after reaching multi-user state)
  • When resuming from suspend
  • When resuming from hibernation
  • When resuming from hybrid-sleep

Why Not fcron or cron?

While fcron is excellent for handling irregular intervals and missed jobs, and cron is great for regular schedules, sometimes simpler is better. If you just need to run backups when your system becomes available, systemd provides a clean, integrated solution without additional scheduling complexities.

Testing

To test your setup without rebooting:

# Test boot trigger
sudo systemctl start backup.service

# Check the status and any error messages
systemctl status backup.service

# Simulate wake from suspend (for testing the handler)
sudo systemctl suspend

Remember to make your backup script executable (chmod +x) and to handle logging appropriately since this runs as a system service.

Troubleshooting

If your service fails to start, check:

  1. The user and group names are correct in the service file
  2. The backup script has the right permissions for the specified user
  3. The logs with journalctl -u backup.service