DEV Community

Cover image for How to setup cronjobs for a Laravel project
Aduramimo Oludare
Aduramimo Oludare

Posted on

How to setup cronjobs for a Laravel project

Tasks like sending email reminders, checking for inactive users, running daily backups, etc., are usually repetitive and as such developers/sysadmins need to leverage the power of cron to automate such tasks.

This tutorial will show how to automate tasks in a laravel application (known as scheduling).

Step 1: On the command line in the directory of your Laravel application, run the following command on the console to create a new command:
php artisan make:command CurrencyCron --command=curr:cron

Step 2: Open the newly-created Command file and edit the logic as follows:
(Directory: app/Console/Commands/CurrencyCron.php)

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Fx_rates;

class CurrencyCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'curr:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info("Cron running!");

          // Database, email or backup logic goes here:

                        $convert = new Fx_rates();
                        $convert->base_curr = "NGN";
                        $convert->target_curr = $currency;
                        $convert->online_forex_rate = $res;
                        $convert->desc = $word;
                        $convert->save();

        }

}

Enter fullscreen mode Exit fullscreen mode

Step 3: Register the command on the Kernel.php file to handle frequency and when you want the command to run.

(Directory: app/Console/Kernel.php)

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
        Commands\CurrencyCron::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('curr:cron')
                 ->timezone('Africa/Lagos')
                 ->dailyAt('08:00');
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 4: Test-run the schedule to see if it will run using:
php artisan schedule:run

Step 5: Finally, we need to add a single cron entry on the server that will take care of all our schedules from the Laravel application.

Type the following commands on the SSH terminal:
a. crontab -e. If this is the first time you are configuring cron on the server, it will prompt for the editor to use.

b. * * * * * /usr/bin/php /var/www/html/your_laravel_app/artisan schedule:run > /tmp/cron_log
This is a directive that runs the cron daemon every minute, checks every schedule you defined under Kernel.php, executes it and dump a log file in the tmp folder for analysis.
Cron will not give information whether or not its commands run successfully, so the only way to troubleshoot is by having a log file.

c. Restart the service by typing:
sudo service cron reload

Discussion (0)