[英]Running a PHP script with crontab
我理解這是問題,但無論我查了多少教程,我都無法讓我的crontab
工作,我正在構建一個網站,它將依賴crontab
每晚重置我數據庫中的特定設置。
這是我的crontab
文件:
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
* * * * * /usr/bin/php -q /var/www/html/cron/index.php
如果我嘗試cd
到/usr/bin/php
我得到
-bash: cd: /usr/bin/php: Not a directory
所以,我cd
“d只是/usr/bin/
這是我發現:
-rwxr-xr-x 1 root root 27216 Feb 10 15:08 pgrep*
lrwxrwxrwx 1 root root 21 Jun 13 09:36 php -> /etc/alternatives/php*
-rwxr-xr-x 1 root root 9049256 Jul 2 11:57 php5*
如果我cd
到/etc/alternatives
我發現:
lrwxrwxrwx 1 root root 13 Jun 13 09:36 php -> /usr/bin/php5*
我回到bin
文件, php5
有*
符號並且是綠色的。
-rwxr-xr-x 1 root root 9049256 Jul 2 11:57 php5*
我的PHP腳本。 非常簡單。 檢查cookie,如果存在,則將其遞增1。 然后我在另一頁上查看結果。 手動這是有效的。 使用crontab
,無法讓它工作。
if (!empty($_COOKIE['cronTest'])) {
$int = $_COOKIE['cronTest'];
$int++;
setcookie("cronTest", $int, time()+3600);
}
最有可能的是, /var/www/html/cron
腳本由www-data
用戶擁有。 根據您的設置,執行cronjob的用戶無權運行此文件。
命令行中沒有$ _COOKIE。 用戶瀏覽器發送cookie。 由於cli不是瀏覽器,因此您無法讀取cookie值。 雖然你可以訪問用戶$ _SESSION,但這是另一個故事。 看看這里是否可以通過命令提示符執行PHP5腳本時讀取cookie /會話值? 了解更多詳情。
你的cronjob線看起來有效,所以問題將是以上幾點之一。 要驗證第一個,請在您的文件中嘗試不使用$ _COOKIE,就像簡單一樣
mkdir('/var/www/html/cron/testdir');
只是為了查看是否可以訪問該文件並在目錄上創建一個目錄。 如果無法訪問,請創建一個新組並添加當前用戶(請查找
ls -al
在/ var / www / html / cron中)和運行cronjob到組的用戶,然后使該組擁有您要運行的文件。 請參閱此問題的已接受答案: 設置用戶權限| Artisan命令不會在代碼中運行,但在命令行上工作正常我會回顧一下如何做到這一點。
對於$ _COOKIE問題,您必須找到另一種解決方案。 例如,使用Redis或Memcached作為緩存服務,可以通過在線和cli配置訪問。
考慮添加
1>> /dev/null 2>&1
在你的cronjob行結束時,如果你不這樣做並讓cron每分鍾運行一次,你將得到大量的日志文件。
為了完成使用php和cli時可能出現的陷阱,總是確保提供文件的完整路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.