laravel使用laravel计划cronjob更新数据库

时间:2018-10-17 09:16:27

标签: mysql laravel eloquent cron scheduled-tasks

我正在尝试运行Eloquent模型以将数据插入数据库,我试图使用Laravel Schedule和cronjobs进行测试运行,下面是我的代码

这是我的App\Console\kernel.php

protected $commands = [
    'App\Console\Commands\test',
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{

    $schedule->command('check:test')->everyMinute();

}

还有我的App\Console\Commands\test

protected $signature = 'check:test';
public function handle()
{

        try {
            $test = new Test([
                "user_id" => 1,
                "data_one"=>321,
            ]);
            $test->save();
            return response()->json('successfully added');

        } catch (exception $e) {
            return response()->json('error', $e);

        }

}

我的crontab -e代码是

* * * * * php /opt/lampp/htdocs/testProj/artisan schedule:run 1>> 
/opt/lampp/htdocs/testProj/schedule.log 2>&1

当执行我得到的日志时,

  

运行计划的命令:'/usr/bin/php7.2''artisan'check:test>'/ dev / null'2>&1

数据库也没有任何变化。 我在做错什么,将不胜感激

1 个答案:

答案 0 :(得分:1)

尝试像crontab -e

中那样使用
* * * * *  php /opt/lampp/htdocs/testProj/artisan schedule:run >> /dev/null 2>&1

kernel.php文件存储区使用laravel登录日志文件

protected $commands = [
     Commands\test::class,
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{

    $schedule->command(Commands\test::class)->everyMinute()->appendOutputTo(storage_path('logs/scheduler.log'));

}

和测试命令应该这样

protected $signature = 'check:test';
public function handle()
{
    try {
        $test = new Test()
        $test->user_id = 1;
        $test->data_one= 321;
        $test->save();
        return $this->info('successfully added');

    } catch (exception $e) {
       return $this->warning('successfully added');
    }
}