How to Execute a Script Periodically Without Using Crontab

command linecron

How to execute a script periodically like crontab does but without using crontab?

Please note this that the executed script should not fire with another script and schedule it with 'sleep' command, what I expect to have same functionality as crontab but it should not be present in crontab list and should not be stop when terminal or session ended,

crontab exactly but without croning it.

Best Answer

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.

Related Question