PHP 函數 ignore_user_abort定時執行任務的實現

來源:互聯網
上載者:User
ignore_user_abort 設定與客戶機斷開是否會終止指令碼的執行。

  本函數返回 user-abort 設定的之前的值(一個布爾值)。


int ignore_user_abort ([ string $value ] )

  

參數 描述
setting 可選。如果設定為 true,則忽略與使用者的斷開,如果設定為 false,會導致指令碼停止運行。
如果未設定該參數,會返回當前的設定。

 注釋:PHP 不會檢測到使用者是否已中斷連線,直到嘗試向客戶機發送資訊為止。簡單地使用 echo 語句無法確保資訊發送,參閱 flush() 函數。


?
1234567891011121314151617181920212223242526 例-1 一個的ignore_user_abort()的例子,配合set_time_limit()函數 和一個死迴圈就可以實現計劃任務功能。  <?php  // Ignore user aborts and allow the script  // to run forever  ignore_user_abort (true);  set_time_limit (0);  echo 'Testing connection handling in PHP' ;  // Run a pointless loop that sometime  // hopefully will make us click away from  // page or click the "Stop" button.  while(1)  {  // Did the connection fail?  if( connection_status () != CONNECTION_NORMAL )  {  break;  }  // Sleep for 10 seconds  sleep (10);  }  // If this is reached, then the 'break'  // was triggered from inside the while loop  // So here we can log, or perform any other tasks  // we need without actually being dependent on the  // browser.  ?>

  

PHP內建函數研究系列第二期,採用PHP函數ignore_user_abort實現計劃任務與持續進程執行個體,並通過一個可檢測效果的執行個體討論ignore_user_abort()函數的作用與用法。

ignore_user_abort() 可以實現當用戶端關閉後仍然可以執行PHP代碼,可保持PHP進程一直在執行,可實現所謂的計劃任務功能與持續進程,只需要開啟執行指令碼,除非 apache等伺服器重啟或有指令碼有輸出,該PHP指令碼將一直處於執行的狀態,初看很實用,不過代價是一個PHP執行指令碼的持續進程,開銷很大,但卻可以 實現很多意想不到的功 能。

其描述為設定與客戶機斷開是否會終止指令碼的執行。


一,函數原型

?
1 int ignore_user_abort ( [bool setting] )

  

二,版本相容
PHP 3 >= 3.0.7, PHP 4, PHP 5

三,函數基礎用法與執行個體
1,函數基礎用法

?
123 <?phpignore_user_abort();?>

說明:調用ignore_user_abort()函式宣告即使客戶機斷開不終止指令碼的執行。

2,結合set_time_limit()函數實現一個迴圈指令碼執行任務

?
12345678 <?phpignore_user_abort();set_time_limit(0);$interval=60*15;do{//執行的業務}while(true);?>

 說明:每隔15分鐘迴圈執行

3,自訂實現檔案輸出並跟蹤ignore_user_abort()函數的執行結果

?
123456789101112 <?phpignore_user_abort ( TRUE );set_time_limit ( 0 );$interval = 10;$stop = 1;do {    if( $stop == 10 ) break;    file_put_contents('liuhui.php',' Current Time: '.time().' Stop: '.$stop);    $stop++;    sleep ( $interval );} while ( true );?>

開啟liuhui.php檔案,檔案內容如下:

Current Time: 1273735029 Stop: 9

其原理是即使用戶端終止指令碼,仍然每隔10秒鐘執行一次,並列印出目前時間與終止點,這樣就可以測試出ignore_user_abort()函數的具體效果。

通過執行個體發現ignore_user_abort()函數非常實用,實現計劃任務,完成後續任務,持續進程等非常有效。更多說明請參與PHP手冊。請關注下一期PHP內建函數研究系列。

 

轉自:http://www.cnblogs.com/wgw8299/articles/2170092.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.