Show Table of Contents
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:
- Create the
systemdunit file that specifies at which stage of the boot process to run the script. This example shows a unit file with a reasonable set ofWants=andAfter=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.targetIf you use this example:- substitute
/usr/local/bin/foobar.shwith 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”. - If you want the
systemdservice to stay active after executing the script, add theRemainAfterExit=yesline to the[Service]section:[Service] Type=oneshot RemainAfterExit=yes ExecStart=/usr/local/bin/foobar.sh - Reload the
systemddaemon:~]#
systemctl daemon-reload - Enable the
systemdservice:~]#
systemctl enable one-time.service - Create the script to execute:
~]#
cat /usr/local/bin/foobar.sh#!/bin/bash touch /root/test_file - If you want the script to run during the next boot only, and not on every boot, add a line that disables the
systemdunit:#!/bin/bash touch /root/test_file systemctl disable one-time.service - Make the script executable:
~]#
chmod +x /usr/local/bin/foobar.sh

Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.