ThinkPHP框架应用之定时任务

定时任务是每个项目必不可少的功能。本文介绍一下如何使用ThinkPHP框架的定时任务。

新建一个定时类

  1. application/admin/command 目录下新建一个 Test.php 文件

  2. 文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class Test extends Command
{
protected function configure(){
$this->setName('test')->setDescription("计划任务 Test");
}

protected function execute(Input $input, Output $output){
$output->writeln('Date Crontab job start...');
/*** 这里写计划任务列表集 START ***/

$this->test();

/*** 这里写计划任务列表集 END ***/
$output->writeln('Date Crontab job end...');
}

private function test()
{
echo '定时任务成功啦~';
}


}

效果图如下:
image

修改 command.php 文件

文件位置 application/command.php

  • 修改内容如下
1
2
3
return [
'app\admin\command\Test'
];

效果图:
image

查看ThinkPHP框架中定时是否添加成功

  • 进入项目目录 (并非是根目录) ,使用命令查看
1
php think

效果图如下:
image

运行定时任务

1
php think test

效果如图:
image

在Linux中添加crontab

  • 编辑crontab
1
2
3
4
5
6
7
8
# 编辑crontab
crontab -e

# 进入编辑模式后添加如下内容
* * * * * php /home/wwwroot/demo.com/think test # 每分钟执行一次计划任务

# 保存退出后重启crontab
/etc/init.d/crond restart

效果图如下:
image
image

0%