Recently I bumped into this problem, and I wanted to share it’s easy solution:
Say you want to execute:
0 6 * * * /home/oraias/cron/restart.sh
PID=$(ps aux | grep tomcat8 | grep -v grep | tr -s ” ” | cut -d” ” -f2)
kill -9 $PID
sudo systemctl start tomcat8
Each day at 6AM cron launches this script. It looks up the PID of a Java process with “tomcat8” in it’s argument list. Kills the process and starts it again. Since this script is being launched as a non-root user, sudo is required for systemctl operation (assuming you configured the sudoers file).
It might happen that the last line of the script silently fails. If this is also your case, check the following options in /etc/sudoers (make sure to open it with sudoedit):
# Disable “ssh hostname sudo <cmd>”, because it will show the password in clear.
# You have to run “ssh -t hostname sudo <cmd>”.
# Refuse to run if unable to disable echo on the tty. This setting should also be
# changed in order to be able to use sudo without a tty. See requiretty above.
Since cron doesn’t launch any TTY, the above options cause sudo to fail silently.
Comment out both to change this behavior.