Hey all

I have a php script that I need to be running 24/7 on a linux platform. I have a dedicated server with centos 5 that I have access via ssh.

The php script is written so that it loops indefinitely. However, it inexplicably hangs after 30 - 60 minutes of runtime and I have had to restart it manually everytime this happens.

However, as a workaround, I'm looking for some type of a cronjob that can just kill the script after every 30 minutes and then restart it automatically.

Being the absolute noob that I am when it comes to linux, I have not been able to make much headway at all into getting this to happen.

Anyone help with what i should do now and what to put into the crontab would be greatly appreciated. Thanks!

Basically this is what I need the cronjob to accomplish

1) start running the script

2) kill the script after 30 minutes of runtime.

3) immediately restart running the script again.

4) kill the script after 30 mins and restart it again ... and so on ...

Edited by sarasara: n/a

7 Years
Discussion Span
Last Post by sknake

When you execute the script write out a PID file. Cron the script to run every 30 minutes and kill itself. You should be able to modify this code to suit your needs:

class pid {

    protected $filename;
    public $already_running = false;
    function __construct($directory) {
        $this->filename = $directory . '/' . basename($_SERVER['PHP_SELF']) . '.pid';
        if(is_writable($this->filename) || is_writable($directory)) {
            if(file_exists($this->filename)) {
                $pid = (int)trim(file_get_contents($this->filename));
                if(posix_kill($pid, 0)) {
                    $this->already_running = true;
        else {
            die("Cannot write to pid file '$this->filename'. Program execution halted.\n");
        if(!$this->already_running) {
            $pid = getmypid();
            file_put_contents($this->filename, $pid);

    public function __destruct() {

        if(!$this->already_running && file_exists($this->filename) && is_writeable($this->filename)) {
$pid = new pid('/tmp');
if($pid->already_running) {
    echo "Already running.\n";
else {
    echo "Running...\n";

Borrowed from:


thanks for the reply. Hope I could make sense of all the code. Way too much code for a total non-programmer such as me!

anyway...the problem is solved...i got a friend to look at it and he gave me a solution that involves running the script as a separate screen and then doing killall screen every 20 mins...worked perfectly!


Thanks for posting your solution back here.

Please mark this thread as solved if you have found an answer to your question and good luck!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.