Reputation: 373
I have a php script on a Linux server that run like:
nohup php myscript.php > /dev/null &
This script needs to be restarted every hour. How can i do that automatically?
Note: Script has a functions that runs indefinetely. So when it starts, it must remain open. So before the script re-run again, it must be killed.
Upvotes: 0
Views: 4293
Reputation: 11812
To add a cronjob use :
crontab -e
then
0 * * * * timeout 3600 nohup php myscript.php > /dev/null &
timeout
param will kill the process after '3600'
second in this example
UPDATE
also you can use
set_time_limit(3600);
in the beginning of your php file that will kill it after 3600
seconds
Upvotes: 2
Reputation: 543
Start the script by a shell script that runs an endless loop and waits for the process to finish. Since you also have an endless loop in your PHP script this will only be if your script is stopped.
Next you write the PID of the script into a text file. You should get the PID with this: http://php.net/manual/en/function.getmypid.php
Next step is to set up a cronjob that runs every hour. This cronjob reads the PID .txt file, deletes it and kills the process.
Since the shell script mentioned in the beginning also has an endless lopp it will restart the php process directly.
Example scripts:
Starter Script:
#!/bin/bash
while true
do
php myscript.php > /dev/null
done
save it e.g. as start.sh and set chmod +x to be able to execute it.
Now you can start it with: nohub ./start.sh &
in .php you do something like this at the beginning:
file_put_contents("/tmp/yourscript.pid", getmypid());
And heres the cron script as bash:
#!/bin/bash
PID=`cat /tmp/yourscript.pid`
rm /tmp/yourscript.pid
kill -9 $PID
you can also to the cron script with php:
<?php
$pid=file_get_contents("/tmp/yourscript.pid");
unlink("/tmp/yourscript.pid");
shell_exec("kill -9 $pid");
Upvotes: 2