Cron Job与Laravel 4

The*_*eed 16 cron command laravel laravel-4

我正试图找出如何在Laravel 4中设置一个cron作业,以及我需要在artisan中运行它的命令.

在Laravel 3中,有一些Tasks似乎不再存在,并且没有关于如何做到的文档......

tom*_*rod 32

下面我详细使用教程commandsLaravel 4:用cron.我已经分为四个步骤,以便更容易理解.


步骤#1:在Laravel 4中创建一个命令:

php artisan command:make RefreshStats
Run Code Online (Sandbox Code Playgroud)

使用上面的命令,Laravel将创建一个RefreshStats.php在目录中命名的文件 app/commands/


RefreshStats.php它是这样的文件:

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class RefreshStats extends Command {

        protected $name = 'command:name';
        protected $description = 'Command description.';

        public function __construct() {
                parent::__construct();
        }

        public function fire(){

        }

        protected function getArguments() {
            return array(
                array('example', InputArgument::REQUIRED, 'An example argument.'),
            );
        }

        protected function getOptions() {
            return array(
                array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
            );
        }

}
Run Code Online (Sandbox Code Playgroud)



步骤#2:RefreshStats文件的简单" 配置 ":

你应该改变这一行:

protected $name = 'command:name';
Run Code Online (Sandbox Code Playgroud)

这样的事情:

protected $name = 'refresh:stats';
Run Code Online (Sandbox Code Playgroud)

如果您不需要参数(选项相同),请更改以下行:

protected function getArguments() {
      return array(
          array('example', InputArgument::REQUIRED, 'An example argument.'),
      );
}
Run Code Online (Sandbox Code Playgroud)

至:

protected function getArguments() {
      return array();
}
Run Code Online (Sandbox Code Playgroud)

而现在注重fire功能.该命令将执行在该函数中编写的源代码.例:

public function fire(){
    echo "Hello world";    
}
Run Code Online (Sandbox Code Playgroud)



步骤#3:注册命令:

您需要注册该命令.所以打开app/start/artisan.php文件,并添加一行如下:

Artisan::add(new RefreshStats);
Run Code Online (Sandbox Code Playgroud)



步骤#4:创建CRON计划任务:

最后,您可以添加计划任务,如下所示:

crontab -e
Run Code Online (Sandbox Code Playgroud)

并添加一行(每30分钟运行一次命令),如下所示:

*/30 * * * * php path_laravel_project/artisan refresh:stats
Run Code Online (Sandbox Code Playgroud)



一切都会自动完成!

  • 很好的教程,tks! (2认同)

Dan*_*ews 15

任务已被命令取代,这些命令在Laravel 4中是相同的,但与Symfony的控制台组件集成,甚至比以前更强大.