What's the best way to stop/start a particular service on a schedule using cron?
I tried running service servicename stop
in a cron job but that didn't appear to work so switched to /etc/init.d/servicename
0 19 * * * /etc/init.d/servicename stop >/dev/null 2>&1
0 7 * * * /etc/init.d/servicename start >/dev/null 2>&1
That appears to work, not sure how consistently yet.
But the strange thing is that I get an e-mail from cron with the following error:
/bin/sh: line 1: 20178 Terminated /etc/init.d/servicename start > /dev/null 2>&1
I only seem to get this error on the starting of the service. The stopping appears to be fine.
Also I thought that the >/dev/null 2>&1
should suppress the e-mailing of notifications. In this case though I'm glad it didn't.
Anyone know of a better way to stop/start services on a schedule, hopefully using cron?
Anyone got any idea what this error is about?
Thanks
You should be able to use
/sbin/service
...and in fact, that's a good habit to get into, since the next release of RHEL/CentOS/etc will probably usesystemd
instead of the legacy/etc/init.d
scripts. If calling/sbin/service
isn't working, you may want to take a look at any error output the command is generating.The
Terminated
error you're getting may be a buggy service control script...if it does something likekillall servicename
it may inadvertently kill the control script, which can result in this error. You're still seeing the error output because this error message is coming from the shell thatcron
starts to run your command, rather than from the command itself. If that's what's happening here, you may want to take a look at the init script and see if you can fix the problem.When debugging errors, it's sometimes a good idea to redirect
stdout
andstderr
to a file rather than/dev/null
(although that wouldn't help in this case).Yes, a better way to handle this is by using a job control utility like Monit. It's available for CentOS and is a clean way to ensure that your daemons are running when they need to, and can be used to start/stop individual or groups of services on a schedule (via cron)... The example where I see cron fall through the cracks is when something happens within the service window (application crash, etc.)
Here's an example with the CUPS printing service...
In a Monit config file somewhere, I'd have a stanza defining the CUPS service, including its PID and start and stop commands.
Running
monit status
Running
monit stop cups
stops the service...monit start cups
starts it. I usually add the monit start and stop commands in the crontab to handle the application startup and shutdown. Monit will ensure that the service is also running during those times (e.g. after a mid-day reboot)...