使用Thinkphp6.0 在Linux搭建簡易的計劃任務
實現流程
1.創建一個自定義指令。
2.編寫sh文件,隨意放置,並給執行權限。
3.Linux執行crontab -e 編輯計劃任務
第一步:自定義指令
1.進入項目根目錄cmd,執行
php think make:command Contrab
輸出:Command:app\command\Contrab created successfully.就說明自動的生成了文件
2.進入app\command\Contrab修改execute方法
protected function execute(Input $input, Output $output)
{
//app\index\controller(命名空間) Index::index(Index控制器下的index方法)
//注意要靜態方法
call_user_func('app\index\controller\Index::index');
}
3.配置config/console.php文件
<?php
return [
'commands' => [
'contrab' => 'app\command\Contrab',
]
];
4.測試是否添加成功
php think
找到Available commands,看下面是否出現了你新添加的contrab,出現則添加成功!
build Build Application Dirs
clear Clear runtime file
contrab
help Displays help for a command
list Lists commands
run PHP Built-in Server for ThinkPHP
start this is a crawl tool!
version show thinkphp framework version
5.測試是否調用成功
php think contrab
輸出:'hello world!' 則表示調用成功
因爲我在Index/index 輸出的是'hello world!'
PS:Thinkphp6自定義命令行的具體文檔地址:https://www.kancloud.cn/manual/thinkphp6_0/1037651
第二步:編寫sh文件
1.新建後綴爲sh文件
2.用編輯器去打開編輯,我用的是Sublime text 3
#!/bin/bash
/usr/local/php7/bin/php /var/www/tp6/think contrab
說明:
/usr/local/php7/bin/php php執行文件路徑
/var/www/tp6/think 項目根目錄加上think
contrab 上面創建的命令名稱
3.保存到任意位置
我是放在/var/www/sh目錄下,記住這個位置,等會有用!
4.給文件執行權限
chmod u+x /var/www/sh/crond.sh
第三步:Linux執行crontab -e
1.編輯計劃任務
crontab -e
輸入i
進入編輯模式
添加 */1 * * * * /var/www/sh/crond.sh
按esc
輸入:wq
保存退出
2.然後重啓crond:
service crond restart
3.完成
現實了每一分鐘輸出了一次 hello world!
當然!具體業務需要各位大佬們自己編寫啦。