To schedule a task to run automatically at system boot using cron, use the @reboot directive in the crontab file. This directive ensures the specified command or script executes once immediately after the system restarts To configure it, open the crontab editor with crontab -e, then add a line using the syntax @reboot [full path to command or script] For example, to run a script located at /root/backup.sh, add @reboot /root/backup.sh to the crontab It is essential to use the full path to the command or script, as the cron environment may not include standard paths like /usr/sbin
The @reboot directive can also be used with commands that require a delay after boot, such as @reboot sleep 300 && date >> ~/date.txt, which waits 300 seconds before executing the date command This is useful for ensuring system services are fully initialized before running dependent tasks. The cron daemon automatically detects changes to the crontab file after saving, so no manual restart is needed
For systems using systemd, an alternative method involves creating a service and timer unit. A service file (e.g., /etc/systemd/system/sched-reboot.service) can be configured to run systemctl --force reboot when started, and a timer file (e.g., /etc/systemd/system/sched-reboot.timer) can be set to trigger the service daily at a specific time using OnCalendar=*-*-* 4:00:00 After creating the files, enable and start the timer with sudo systemctl enable sched-reboot.timer and sudo systemctl start sched-reboot.timer
For scheduled reboots at specific times, such as daily at 3 AM, use a standard cron entry like 0 3 * * * root /usr/sbin/reboot -f >> /var/log/reboot.log 2>&1 This command uses the full path to reboot to avoid PATH issues and includes logging to track execution The @reboot directive is specifically for tasks that should run once at boot, not for recurring reboots