注:使用Crontab定時執行php腳本文件
1. 安裝crontab
yum install crontabs
說明:
/sbin/service crond start //啟動服務
/sbin/service crond stop //關閉服務
/sbin/service crond restart //重啟服務
/sbin/service crond reload //重新載入配置
查看crontab服務狀態:service crond status
手動啟動crontab服務:service crond start
查看crontab服務是否已設置為開機啟動,執行命令:ntsysv
加入開機自動啟動:
chkconfig –level 35 crond on
注:可以使用systemctl list-units命令查看crond服務有沒有開啟
2.crontab -e,進入編輯頁面,i鍵進入編輯模式
參 數:
-e 編輯該用戶的計時器設置。
-l 列出該用戶的計時器設置。
-r 刪除該用戶的計時器設置。
-u<用戶名稱> 指定要設定計時器的用戶名稱。
crontab 格式:
基本格式 :
分鍾 小時 日 月 星期 命令
* * * * * *
第1列表示分鍾1~59 每分鍾用*或者 */1表示
第2列表示小時1~23(0表示0點)
第3列表示日期1~31
第4列 表示月份1~12
第5列標識號星期0~6(0表示星期天)
第6列要運行的命令
記住幾個特殊符號的含義:
“*”代表取值范圍內的數字,
“/”代表”每”,
“-”代表從某個數字到某個數字,
“,”分開幾個離散的數字
本例中執行:* */1 * * * /usr/bin/php /www/wwwroot/snow/test.php 設置每分鍾執行一次test.php文件 Esc->:wq退出保存 (*/1 * * * *也代表每一分鍾執行)
注:/usr/bin/php //調用php
/www/wwwroot/snow/test.php //需要執行的php文件
3.可以執行命令:tail -f /var/log/cron可以查看corntab的執行情況(ctrl+c退出)
4.thinkphp 中的實踐操作:
1)控制器:
namespace app\admin\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;
class AutoTest extends Command
{
protected function configure()
{
$this->setName('autoTest')->setDescription("定時任務測試");
}
//調用這個類時,會自動運行execute方法
protected function execute(Input $input, Output $output)
{
$output->writeln('Date Crontab job start...');
/*** 這里寫計划任務列表集 START ***/
/**需要執行的代碼**/
/*** 這里寫計划任務列表集 END ***/
$output->writeln('Date Crontab job end...');
}
}
2)command.php中加入:
return [
'app\admin\command\AutoTest',
];
3)定時任務:
*/1 * * * * sudo -u www /www/server/php/72/bin/php /www/wwwroot/project/think autoTest
參考鏈接:https://blog.csdn.net/jueyan520/article/details/86242257 (感謝分享)
https://www.cnblogs.com/jingmin/p/9687905.html(感謝分享)
https://blog.csdn.net/zixuan701/article/details/88536003 (感謝分享)