How can I stop a systemd service with cron?

6,736

Probably because you haven't told cron to use root.

* * * * * root /bin/systemctl stop nginx

That will execute the command every minute, regardless of the nginx status (started or not)

So that being said, if the goal is to make sure nginx is never started, why not just disable it?

systemctl disable nginx

==Edit==

Good point made by Aaron Copley in the comments, in order to make sure nginx wont be started even after boot the command should be;

systemctl mask nginx
Share:
6,736

Related videos on Youtube

Jimbotron
Author by

Jimbotron

Updated on September 18, 2022

Comments

  • Jimbotron
    Jimbotron over 1 year

    I have a simple crontab entry that is supposed to stop a service, yet it does not work.

    * * * * * systemctl stop nginx
    

    I even tried:

    * * * * * /bin/systemctl stop nginx
    

    Since that't the location of systemctl that which command shows.

    That line works with root user, yet not working with root's crontab.

    And by not working, I mean the service is not shut down. I can confirm the server is still running and systemctl status nginx show it's active.

    What am I doing wrong?

    • guzzijason
      guzzijason over 5 years
      What do your cron logs say?
    • Michael Hampton
      Michael Hampton over 5 years
      What was the output of systemctl status nginx?
  • guzzijason
    guzzijason over 5 years
    This is not always true - if the entry is put into /etc/crontab or /etc/cron.d/*, then yes you will need to include the user in the crontab entry. However, if you add this job to root's individual crontab (such as /var/spool/cron/root, or crontab -e -u root) then there is no need to specify the user.
  • Jimbotron
    Jimbotron over 5 years
    That was just an example, I could have put 10 16 * * *, this was just to illustrate that the problem is not due to time not properly being set. The point is, I am creating crontab entry with root user and the service is not shutting down.
  • Aaron Copley
    Aaron Copley over 5 years
    systemctl disable nginx will only prevent it from starting on boot and won't stop it from being started as a dependency of another service. You want systemctl mask nginx to prevent the service from being able to be started at all.