23.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
    [Unit]
    # The script needs to execute after:
    # network interfaces are configured
    Wants=network-online.target
    After=network-online.target
    # all remote filesystems (NFS/_netdev) are mounted
    After=remote-fs.target
    # 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
    After=time-sync.target
    
    [Service]
    Type=oneshot
    ExecStart=/usr/local/bin/foobar.sh
    
    [Install]
    WantedBy=multi-user.target
    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:
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/usr/local/bin/foobar.sh
  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
    #!/bin/bash
    
    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:
    #!/bin/bash
    
    touch /root/test_file
    systemctl disable one-time.service
  7. Make the script executable:
    ~]# chmod +x /usr/local/bin/foobar.sh