如何控制 PHP 的最長執行時間。
在執行 PHP 腳本的時候有可能因為程式邏輯上的問題或是為了取得外部的資料導致執行時間過久,而讓使用者等待回應的時間過長帶來不好的體驗, 因此在 PHP 本身一些常用的函式庫或是伺服器設定會讓開發者設定 timeout 的時間。
nginx
- fastcgi_connect_timeout
- fastcgi_send_timeout
- fastcgi_read_timeout
php-fpm
- php-fpm.conf 的 request_terminate_timeout
max_execution_time 和 set_time_limit 也能限制腳本執行的時間但是似乎在某些場景是有問題的。
curl
- CURLOPT_TIMEOUT
- CURLOPT_TIMEOUT_MS
- CURLOPT_CONNECTTIMEOUT
- CURLOPT_CONNECTTIMEOUT_MS
- CURLOPT_DNS_CACHE_TIMEOUT
mysql
- innodb_lock_wait_timeout
- libmysql 的 MYSQL_OPT_READ_TIMEOUT 和 MYSQL_OPT_WRITE_TIMEOUT
memcached
- bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )
- Memcached 要另外實現
redis
- $redis->connect(‘127.0.0.1’, 6379, 2.5); // 2.5 sec timeout.
- $redis->pconnect(‘127.0.0.1’, 6379, 2.5, ‘x’); // x is sent as persistent_id and would be another connection the the three before.