1、方法一:v3.2.1
①、ThinkPHP/Library/Behavior/CronRunBehavior.class.php文件
在这里首先要说的就是这个自动执行任务文件,官方所给的这个文件存在BUG,我是用的是v3.2.1版本,后面的版本是否有改正大家可以尝试一下。
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <?php
namespace Behavior;
class CronRunBehavior
{
public function run(& $params )
{
if (C( 'CRON_CONFIG_ON' )) {
$this ->checkTime();
}
}
private function checkTime()
{
if (F( 'CRON_CONFIG' )) {
$crons = F( 'CRON_CONFIG' );
} else if (C( 'CRON_CONFIG' )) {
$crons = C( 'CRON_CONFIG' );
}
if (! empty ( $crons ) && is_array ( $crons )) {
$update = false;
$log = array ();
foreach ( $crons as $key => $cron ) {
if ( empty ( $cron [2]) || $_SERVER [ 'REQUEST_TIME' ] > $cron [2]) {
G( 'cronStart' );
R( $cron [0]);
G( 'cronEnd' );
$_useTime = G( 'cronStart' , 'cronEnd' , 6);
$cron [2] = $_SERVER [ 'REQUEST_TIME' ] + $cron [1];
$crons [ $key ] = $cron ;
$log [] = 'Cron:' . $key . ' Runat ' . date ( 'Y-m-d H:i:s' ) . ' Use ' . $_useTime . ' s ' . "\r\n" ;
$update = true;
}
}
if ( $update ) {
\Think\Log::write(implode( '' , $log ));
F( 'CRON_CONFIG' , $crons );
}
}
}
}
|
②、tgs.php
在Application/Common/Conf文件夹中新建tags.php文件,进行标签设置。
1 2 3 4 5 6 | <?php
return array (
'app_begin' => array ( 'Behavior\CronRunBehavior' ),
);
|
③、config.php
在Application/Common/Conf文件夹中的config.php文件进行自动运行配置。
1 2 3 4 5 6 7 8 | <?php
return array (
'CRON_CONFIG_ON' => true,
'CRON_CONFIG' => array (
'测试执行定时任务' => array ( 'Home/Index/crons' , '5' , '' ),
),
);
|
④、IndexController.class.php
在Application/Home/Controller/IndexController.class.php文件中进行定时执行任务的编写。
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 32 33 34 35 36 37 38 39 | <?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller
{
public function index()
{
$contents = file_get_contents ( "test.txt" );
var_dump( $contents );
exit ;
$this ->assign( "contents" , $contents );
$this ->display();
}
public function crons()
{
file_put_contents ( "test.txt" , date ( "Y-m-d H:i:s" ) . "执行定时任务!" . "\r\n<br>" , FILE_APPEND);
}
}
|
这样定时执行任务我们就写好了,每隔5秒我们访问任何项目的url,然后查看根目录下的test.txt文件就会发现里面的内容变化。
注意:当你修改间隔时间时会发现没有生效,这是你需要将Runtime/Data文件夹下的缓存文件删除,间隔时间缓存存放在CRON_CONFIG.php文件中。
2、方法2:v3.2.2
此方法和方法一没有多大的区别。
①、tags.php
在/Application/Common/Conf目录下新建tags.php文件。(此和方法一处一样)
1 2 3 4 5 6 | <?php
return array (
'app_begin' => array ( 'Behavior\CronRunBehavior' ),
);
|
②、crons.php
在/Application/Common/Conf目录下新建crons.php文件。(此处和方法一有区别,注意区分。)
1 2 3 4 5 6 7 | <?php
return array (
'cron' => array ( 'myplan' , 2, nextruntime),
);
|
③、myplan.php
在/Application/Common/目录下新建 Cron文件夹,里面新建文件myplan.php文件。
1 2 3 | <?php
echo date ( "Y-m-d H:i:s" ). "执行定时任务!" . "\r\n<br>" ;
|
此时我们就可以访问项目的url,然后我们会发现在Application/Runtime/目录下生成了~crons.php文件,文件内容如下:
1 2 3 4 5 6 7 8 9 10 11 | <?php
return array (
'cron' =>
array (
0 => 'myplan' ,
1 => 60,
2 => 1398160322,
),
);
?>
|
推荐教程:thinkphp教程
以上就是thinkphp设置定时执行任务的方法的详细内容