Cronjob, every 20 minutes. Starting direct after reboot
running a cronjob like
*/15 * * * * sh /home/me/skript.sh >> /home/me/out.log 2>&1
will execute the skript.sh
every 15 minutes. Starting the computer at 12:10, I have to wait 5 minutes.
Is there a way to get the cronjob starting immediately after reboot and then every 15 minutes?
Thanks, Martin
systemd to the rescue
This is not possible with cron
but systemd
can do that.
You need to create two systemd units, one that starts your script, and one for the timer.
file /etc/systemd/system/my-fifteen-minutes.timer
:
[Unit]
Description=15 minute timer
[Timer]
# start this 0 minutes after boot:
OnBootSec=0 min
# ... and then every 15 minutes:
OnActiveSec=15 min
[Install]
WantedBy=multi-user.target
file /etc/systemd/system/my-fifteen-minutes.service
(note the different extension):
[Unit]
Description=My script
[Service]
Type=oneshot
ExecStart=/bin/sh -c "/home/me/skript.sh >> /home/me/out.log 2>&1"
User=me
Put these files in the directory /etc/systemd/system
and enable the timer with
# make systemd aware of them
sudo systemctl daemon-reload
# make sure the timer is engaged at startup
sudo systemctl enable my-fifteen-minutes.timer
# start the timer "now" (without rebooting):
sudo systemctl start my-fifteen-minutes.timer
# examine the status:
systemctl status my-fifteen-minutes.timer my-fifteen-minutes.service
The command systemctl status my-fifteen-minutes.timer
will show something like
● my-fifteen-minutes.timer - 15 minute timer
Loaded: loaded (/etc/systemd/system/my-fifteen-minutes.timer; enabled; vendor preset: enabled)
Active: active (waiting) since Sun 2018-07-01 14:42:05 CEST; 1s ago
Trigger: Sun 2018-07-01 14:57:05 CEST; 14min left
Jul 01 14:42:05 stratum9 systemd[1]: Started 15 minute timer.
This means: The timer was triggered 1s ago
and will be triggered again in ~14 minutes (at "Sun 2018-07-01 14:57:05 CEST").
Note that the timer and the service are two different things, and you need to define both. By default, a timer unit starts a service unit with the same name (except for the extension .timer
vs. service
), i.e. foo.timer
would control foo.service
(you can override that, though). The timer unit just defines when something happens to the service unit, and the service unit defines the actual action (in your case: start the script /home/me/skript.sh
).
Further reading:
- timers: https://www.freedesktop.org/software/systemd/man/systemd.timer.html
- services: https://www.freedesktop.org/software/systemd/man/systemd.service.html
- units (applies to both timers and services): https://www.freedesktop.org/software/systemd/man/systemd.unit.html