脚本超时的finally子句替代 [英] Finally clause alternative for script timeout

查看:241
本文介绍了脚本超时的finally子句替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我训练一个PHP脚本作为一个良好的cron作业运行。为了逃避无限循环,我已经添加了 set_time_limit

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.

据我所知, PHP的功能。我想有这样的功能来清理,例如,当达到时间限制时解除链接文件。

As far as I know there is not finally clause functionality for PHP. I would like to have such functionality to cleanup, like unlinking files when the time limit is reached.

这将是一个替代的方法来完成这个?

What would be an alternative way to accomplish this?

推荐答案

Bruce Aldridge已经回答,如何达成。

我以另一种方式告诉你: a href =http://en.wikipedia.org/wiki/RAII =nofollow> RAII模式(不是说越好或越差)

示例:

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);
            }
        }
    }
}

此类将用于打开文件,所有文件将在脚本终止时关闭和取消链接。此示例专门针对您的问题 - 通常使用1个对象来访问1个资源。

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.

这篇关于脚本超时的finally子句替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆