第一步:
a.App/模塊/ 下創建command文件夾
b.我這邊是創建在crontab模塊里面,在command文件夾下創建一個Task.php文件(具體名字自己根據需求定)

c.復制下面的代碼到Task.php
<?php namespace app\crontab\command; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; use think\Db; class Task extends Command { protected function configure() { $this->setName('task') ->setDescription('定時計划測試:每分鍾插入一條數據'); } protected function execute(Input $input, Output $output) { // 輸出到日志文件 $output->writeln("TestCommand:"); // 定時器需要執行的內容 $data = [ 'name'=>'zxm22', 'addr'=>'上海' ]; db('blog')->insert($data); $output->writeln("end...."); } }
第二步:在APP/command.php里面加上

第三步:在linux下設置crontab定時計划任務(我的項目文件放在/var/www/mytp5)即可
crontab -l //計划任務列表
crontab -e //編輯新增
crontab -r //刪除

可參照:(查看php執行路徑 whereis php)
1、配置command.php文件,目錄在application/command.php 2、建立命令類文件,新建application/index/command/Test.php <?php namespace app\index\command; use think\console\Command; use think\console\Input; use think\console\Output; class Test extends Command { protected function configure() { $this->setName('test')->setDescription('Here is the remark '); } protected function execute(Input $input, Output $output) { $output->writeln("TestCommand:"); } } 3、命令行下運行php think test ,將輸出 TestCommand:,說明命令行已經成功 4、在linux系統配置crontab定時任務,一般目錄在下圖 4、根據自己的用戶角色,編輯文件,如我是root用戶,打開root文件,配置contab */1 * * * * cd /項目路徑 && /php路徑/php think test >> tmp/test.log 2>&1 這句話的意思是沒一分鍾執行一遍 test/index,日志存儲在項目目錄的 tmp/test.log文件里 根據上面的步驟就可以把定時任務跑起來了,很簡單吧!!!
