The cron daemon is the standard task scheduler in Linux, traditionally used to run scripts at specific times or intervals (e.g., every day at midnight or every 5 minutes). However, system administrators frequently need scripts to execute immediately after the system boots up—such as starting a custom background service, mounting network drives, or sending a notification that a server has restarted.
While you could write a complex `systemd` service file to achieve this, the simplest and fastest method is using the special @reboot directive within your user’s crontab.
Understanding the @reboot Directive
Unlike standard cron expressions that rely on asterisks to denote time, @reboot is a non-standard macro supported by most modern cron implementations (including Vixie cron, which is standard on Ubuntu and Debian). When you use this directive, the cron daemon will execute the specified command exactly once, shortly after the cron service itself starts during the boot process.
How to Schedule a Boot Task
Follow these steps to add a startup script using crontab.
- Open your terminal.
- To edit the crontab for your current user, type the following command and press Enter:
crontab -e - If this is your first time running the command, you will be prompted to select an editor (Nano is usually the easiest option for beginners).
- Scroll to the very bottom of the file, past all the commented instructional lines.
- Add your new directive using the following syntax:
@reboot /absolute/path/to/your/script.sh - Save the file and exit the editor (in Nano, press
Ctrl+O,Enter, thenCtrl+X).
Crucial Best Practices for @reboot Tasks
Because these scripts run during the chaotic boot process, they often fail if they are not configured carefully. Keep the following rules in mind:
1. Always Use Absolute Paths
During the boot sequence, your user’s normal environment variables (like the $PATH variable) have not been fully loaded. If your script relies on external commands like python3, curl, or node, the script will likely fail because cron cannot find them.
You must specify the absolute path for both the script and any commands inside it. For example, instead of writing:@reboot python3 /home/user/startup.py
You should write:@reboot /usr/bin/python3 /home/user/startup.py
2. Add a Sleep Delay for Network Tasks
The cron daemon starts very early in the boot process, often before the network interfaces have finished initialising. If your script attempts to download a file or ping an external server immediately, it will fail because the internet connection is not ready yet.
To prevent this, you can instruct the script to pause for a specific number of seconds before executing. Use the sleep command inline:
@reboot sleep 30 && /usr/bin/python3 /home/user/network_script.py
This tells cron to wait exactly 30 seconds after booting before executing the Python script, ensuring the network stack is fully operational.