How to execute a script periodically without using crontab?
The modern option is to use a systemd
timer unit. This requires creating a systemd
unit which defines the job you want to periodically run, and a systemd.timer
unit defining the schedule for the job.
Assuming you want to run the job as regular user, put these files in $HOME/.config/systemd/user
:
my-job.service
[Unit]
Description=Job that needs periodic execution
[Service]
ExecStart=/path/to/your/script
my-job.timer
[Unit]
Description=Timer that periodically triggers my-job.service
[Timer]
OnCalendar=minutely
Then enable the newly created units, and start the timer:
$ systemctl --user enable my-job.service my-job.timer
$ systemctl --user start my-job.timer
To verify that the timer is set:
$ systemctl --user list-timers
NEXT LEFT LAST PASSED UNIT ACTIVATES
Wed 2016-11-02 14:07:00 EAT 19s left Wed 2016-11-02 14:06:37 EAT 3s ago my-job.timer my-job.service
journalctl -xe
should show log entries of the job being run.
Refer to man systemd.timer
for the many options for configuring timer behaviour (including randomised starting, waking the computer, persistence across downtime, timer accuracy, etc.), and to man systemd.unit
for excellent documentation on systemd
and systemd
units in general.
You could run a script with at
and have it reschedule itself as its final instruction. For instance like this:
$ cat > $HOME/my.job <<END
do this
do that
cat "$HOME/my.job" | at now + 5 minutes
END
$ sh ~/my.job
To stop the job, remove it from the at
queue:
$ atq
5 Wed Nov 2 11:25:00 2016 a zwets
$ atrm 5
Or simply remove the file my.job
so the next execution of cat "$HOME/my.job"
will error so at
will not be invoked and the rescheduling doesn't happen.