1

I would like to set up a Timer which will stop a service, execute a script and restart the service.

One of the possibilities is to use

Type=oneshot
ExecStartPre=/bin/systemctl stop myservice
ExecStart=/usr/local/bin/myscript.sh
ExecStartPost=/bin/systemctl start myservice

Another one is to have myscript.sh handling the whole thing, including systemctl.

I find it awkward, though, to use systemctl within a service declaration, when there may be systemd built-in mechanisms to interact with services. Is there a cleaner way to perform these operations?

  • Can you give more context here? Why do you need myservice to be stopped during the run of myscript.sh? There's nothing essentially wrong with using systemctl inside a service (and you probably won't find a solution that doesn't involve using it), but perhaps, depending on what myscript.sh is doing, you could just hook it into myservice.service directly (in an ExecStartPre=, perhaps checking if it needs to run) and then just having the timer launch a systemctl restart myservice instead... Just an idea. Having more context on what you're trying to do would help here. – filbranden Nov 23 '18 at 19:17
  • @FilipeBrandenburger: this is a Timer which will perform a backup. The service backed up needs first to be stopped, then restarted afterwards. – WoJ Nov 23 '18 at 19:22
1

By (ab?)using the WatchdogSec the service will terminate when it fails to acknowledge within the time. It will then restart, but execute the script first.

WatchdogSec={interval}
Restart=on-watchdog
ExecStopPost=/script.sh

ref: WatchdogSec

Having the service being able to be backed up while running would be a much nicer service.

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.