24.5. Scheduling a Job to Run on Next Boot Using a systemd Unit File

The cron, anacron, at, and batch utilities allow scheduling jobs for specific times or for when system workload reaches a certain level. It is also possible to create a job that will run during the next system boot. This is done by creating a systemd unit file that specifies the script to run and its dependencies.
To configure a script to run on the next boot:
  1. Create the systemd unit file that specifies at which stage of the boot process to run the script. This example shows a unit file with a reasonable set of Wants= and After= dependencies:
    ~]# cat /etc/systemd/system/one-time.service
    # The script needs to execute after:
    # network interfaces are configured
    # all remote filesystems (NFS/_netdev) are mounted
    # name (DNS) and user resolution from remote databases (AD/LDAP) are available
    After=nss-user-lookup.target nss-lookup.target
    # the system clock has synchronized
    If you use this example:
    • substitute /usr/local/bin/foobar.sh with the name of your script
    • modify the set of After= entries if necessary
    For information on specifying the stage of boot, see Section 10.6, “Creating and Modifying systemd Unit Files”.
  2. If you want the systemd service to stay active after executing the script, add the RemainAfterExit=yes line to the [Service] section:
  3. Reload the systemd daemon:
    ~]# systemctl daemon-reload
  4. Enable the systemd service:
    ~]# systemctl enable one-time.service
  5. Create the script to execute:
    ~]# cat /usr/local/bin/foobar.sh
    touch /root/test_file
  6. If you want the script to run during the next boot only, and not on every boot, add a line that disables the systemd unit:
    touch /root/test_file
    systemctl disable one-time.service
  7. Make the script executable:
    ~]# chmod +x /usr/local/bin/foobar.sh