![](/img/trans.png)
[英]PHP, javascript, cronjobs - Ajax test if user is online fail
[英]PHP Cronjobs using javascript/AJAX
我有一個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>
這些方法不會影響用戶請求時間;)
多謝你們
您可以讓調用的PHP腳本模擬連接的結束。 這意味着它可以向用戶發送任意輸出,然后強制關閉用戶的連接,但仍保持服務器端運行。
請參閱以下文章: http : //php.net/manual/zh/features.connection-handling.php
評論中有一些示例。
在PHP方面,您可以使用Connection HTTP標頭告訴瀏覽器不要等待其他數據。 有關更多詳細信息,請參見https://www.zulius.com/how-to/close-browser-connection-continue-execution/ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.