16

我正在尝试找出如何在 Laravel 4 中设置 cron 作业,以及我需要在 artisan 中运行的命令。

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

4

4 回答 4

37

下面我详细介绍一个使用croncommands的教程。Laravel 4为了更容易理解,我分为四个步骤。


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

php artisan command:make RefreshStats

RefreshStats.php使用上面的命令,Laravel 将在目录中 创建一个名为的文件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),
            );
        }

}



第 2步:RefreshStats 文件的简单“配置”:

你应该改变这一行:

protected $name = 'command:name';

像这样:

protected $name = 'refresh:stats';

如果您不需要参数(与 options 相同),请更改此行:

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

至:

protected function getArguments() {
      return array();
}

现在注意功能fire。该命令将执行在该函数中编写的源代码。例子:

public function fire(){
    echo "Hello world";    
}



第 3 步:注册命令:

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

Artisan::add(new RefreshStats);



第 4 步:创建CRON计划任务:

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

crontab -e

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

*/30 * * * * php path_laravel_project/artisan refresh:stats



一切都会自动运行

于 2015-07-22T10:09:03.690 回答
15

任务已被替换为命令,这在 Laravel 4 中是一样的,但集成了 Symfony 的控制台组件,甚至比以前更强大。

于 2013-01-25T11:40:50.157 回答
4

或者,如果你不喜欢命令,有一个非官方的 Laravel 4 cron 包:https ://github.com/liebig/cron

于 2013-07-25T19:05:12.790 回答
0

好的,所以我发现对于在 laravel 4.2 中设置 crons 很有用。

于 2019-12-14T21:22:27.103 回答