Search code examples
laravelamazon-web-servicesnginxamazon-elastic-beanstalk

Cron job not working in Elastic Beanstalk


I have deployed a laravel application in Elastic Beanstalk with Load Balancing. I have to backup my database daily and store it in s3 bucket so I am using Laravel-backup-server package. And I have set up cronjob using Nginx. When I manually run php artisan schedule:run in my local machine it works fine but when I deploy to Aws it's not running the cron job. My setup looks something like this

.ebextensions/cron-setup.config

"/etc/cron.d/cron_example":
    mode: "000644"
    owner: root
    group: root
    content: |
      * * * * * root . /opt/elasticbeanstalk/support/envvars && /usr/bin/php /var/www/html/artisan schedule:run 1>> /laralog.log 2>&1
commands:
  rm_old_cron:
    command: "rm -fr /etc/cron.d/cron_example.bak"
    ignoreErrors: true

app\Console\Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('backup:run --only-db')
    ->everyMinute();
    Log::info('running cron');
    
}

I am using cloudwatch for logging. And when I run php artisan schedule:run locally I am getting a log in cloud watch. But when I deploy it to Elastic beanstalk and set up cron in ngnix there is no log.

enter image description here

Also, I tried to use this config which I found in Github I didn't make any changes but not working

    files:
    "/etc/cron.d/schedule_run":
        mode: "000644"
        owner: root
        group: root
        content: |
            * * * * * root . /opt/elasticbeanstalk/support/envvars && /usr/bin/php /var/www/html/artisan schedule:run 1>> /dev/null 2>&1

commands:
    remove_old_cron:
        command: "rm -f /etc/cron.d/*.bak"

Solution

  • After several efforts I found a alternative way to run cron job easily

    Create a route

    routes/web.php

    Route::get('/cron/run',[HomeController::class, 'cron'])->name('cron');
    

    create a function in the HomeController

    public function cron()
    {
        \Artisan::call("schedule:run");
        return 'run cron successful';
    }
    

    Run the URL every minute using https://cron-job.org/en/