0

I have a program running via Systemd and I'm trying to figure out how to start/stop it at certain times. It's a persistent program (transmission).

Currently I have a crontab with the following lines:

0 8 * * * systemctl stop transmission-daemon
0 20 * * * systemctl start transmission-daemon

I'm struggling to translate this to a Systemd timer file.

Additionally, is it possible to have systemd (or cron) check if the service should be running or not based on the current time in the event of a reboot?

Thanks for your help, if this has been asked before please point me to specific examples of exactly this kind of thing. Most of what I can find is how to run a service in 15 minute intervals and similar.

0

It may be simpler to have a timer that runs a script once an hour and at reboot, and that script checks whether the current hour is one in which the daemon should be running or not, and then if necessary (possibly after a systemctl is-active $service check) starts or stops the service. This script could also check for a file, or act on other business logic to determine whether things need to be running or not, e.g. a touch ~/.fooservice-do-not-run file could disable things, or if the load is too high, etc.

  • So I would need a new unit file for the script and then a separate timer file, right? – Eric Wolf Sep 22 '16 at 20:22
0

To start services via timers in systemd, you use two unit files. A X.service file to describe the actual service, and a X.timer file to describe when the service is to be started.

To turn a service on and off as you describe, the best I can think of is to have a separate Xoff pair of unit files, where the service files mutually conflict with each other. The Xoff service doesn't really do anything, it is just there to “run” when the real service is off.

To give you an idea, here is a toy example with a service sleep that is turned on every even minute, and turned off every odd minute.

sleep.service:

[Unit]
Description=Test service not doing anything real.
Conflicts=sleepoff.service

[Service]
ExecStart=/usr/bin/sleep 1d

sleep.timer:

[Unit]
Description=Timer to start the sleep service.

[Timer]
OnCalendar=*:0/2

sleepoff.service:

[Unit]
Description=Dummy service "running" when the real unit is off.
Conflicts=sleep.service

[Service]
Type=oneshot
ExecStart=/usr/bin/true
RemainAfterExit=true

sleepoff.timer:

[Unit]
Description=Timer to stop the sleep service.

[Timer]
OnCalendar=*:1/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.