开发者

Finally clause alternative for script timeout

I'm training a PHP script to run as a well behaved cron job. To escape infinite loops and such I've added set_time_limit.

As far as I know there is not finally clause functionality for PHP. I would like to have such functionality to cleanup, like unli开发者_如何学JAVAnking files when the time limit is reached.

What would be an alternative way to accomplish this?


Bruce Aldridge already answered, how it can be reached.
I show you another way: RAII pattern (not to say that is better or worse)
Example:

class AutoUnlinker
{
    private $files;

    public function OpenFile($filepath, $mode)
    {
        $handler = fopen($filepath, $mode);
        $this->files[$filepath] = $handler;
        return $handler;
    }

    public function __destruct()
    {
        if (!empty($this->files))
        {
            foreach ($this->files as $filepath => $handler)
            {
                if (!empty($handler)) fclose($handler);
                if (file_exists($filepath)) unlink($filepath);
            }
        }
    }
}

If this class will be used for opening files, all files will be closed and unlinked on script termination. This example specially for your question - usually 1 object being used to give access to 1 resource.


http://php.net/manual/en/function.register-shutdown-function.php

actually, this won't run on script timeout. and it would be better to handle catches for infinite loops in the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜