PHP Cronjobs使用javascript / AJAX

时间:2013-01-09 20:06:09

标签: php javascript ajax cron backup

我有一个运行数据库备份的php脚本,并在没有任何特定html输出的情况下对其进行压缩。此脚本包括时间检查,以避免在db中存储指定的延迟之前执行。 现在问题是我无法使用服务器cronjob任务,因为Web服务器不支持它。

所以我会创建一个javascript函数,应该在每次访问时调用php脚本(是的,这对我的目的来说已足够)但不会延迟访问该页面的用户,因为它需要大约1分钟才能结束该过程。 是否可以在不等待响应的情况下运行脚本?当用户会话终止时,php脚本还可以继续运行吗?

我认为类似于: http://drupal.org/project/poormanscron

提前致谢

修改 解决方案1(仅限PHP): 把它放在我的输出之前:

public static function cronjob() {
        ignore_user_abort(true); // optional
        session_write_close();//close session file on server side to avoid blocking other requests
        header("Content-Encoding: none");//send header to avoid the browser side to take content as gzip format
        header("Content-Length: ".ob_get_length());//send length header
        header("Connection: close");//or redirect to some url: header('Location: http://www.google.com'); 
        ob_end_flush();flush();//really send content, can't change the order:1.ob buffer to normal buffer, 2.normal buffer to output
        //fastcgi_finish_request(); // important when using php-fpm!
        // Do processing here 
        sleep(5);
        require_once("./cron_job.php");
        exit();
}
        ob_start(); // will be closed in backup function
        register_shutdown_function('cronjob');

解决方案2(使用javascript):

1)在

中创建一个包含cronjobs的文件

2)将这个javascript代码放在你的html中:

<script type="text/javascript">
    // cron job
    $.get('./cron_job.php');
</script>

这些方法不会影响用户请求时间;)

谢谢你们

2 个答案:

答案 0 :(得分:0)

您可以让您调用的PHP脚本模拟连接的结尾。这意味着它可以向用户发送一些任意输出,然后强制用户的连接关闭但仍然继续运行服务器端。

请参阅以下文章:http://php.net/manual/en/features.connection-handling.php

评论中有一些例子。

答案 1 :(得分:0)

在PHP端,您可以告诉浏览器不要使用Connection HTTP标头等待更多数据。看到 https://www.zulius.com/how-to/close-browser-connection-continue-execution/了解更多详情。