Managing Cronjobs with Laravel

Published by Manan Patel on

Laravel provides a feature to run specific jobs through only one cron on the server.  It automatically manages all the jobs through the artisan command you don’t need to set multiple jobs on the server to execute in the specific time and specific interval.

We can manage a task on the server that executes scripts which helps in sending daily/weekly reports to email id or update records in the database from our laravel application.

The main use of cron job is in updating the databases, sending the emails, generate reports, executing the time-consuming tasks etc. We can also delete or create files from the server with the help of Cron Job.

In the unix based machines, there is a configuration file called crontable which is also known as Crontab. From this file system manages cron jobs for that particular user in which it is placed.

To set a cron job with the script, there are various steps you have to follow.

Step1:

Create A New Command Class

Firstly, we will generate a custom command by running following php artisan command in the terminal which will generate a class file in the app/Console/Commands/ directory of your laravel application.

php artisan make:console CustomCommand

After running this command you will get a message ‘Console command created successfully in your terminal and you will see there is an auto-generated class file at app/Console/Commands/CustomCommand.php with default signature. You can also assign the terminal command name by using –command option as under.

php artisan make:console CustomCommand --command=custom:command

Step 2:  

Write a script for the task

Whenever the above command will be executed in your terminal It creates a class with handle method which is called when the task is scheduled to execute. Here I am taking a sample script to delete all inactive users from the database in handle method.

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;

class CustomCommand extends Command {

    /**
    * The name and signature of the console command.
    * @var string
    */

    protected $signature = 'custom:command';

    /**
    * The console command description.
    * @var string
    */

    protected $description = 'Delete all inactive users';

    /**
    * Create a new command instance.
    * @return void
    */

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

    /**
    * Execute the console command.
    * @return mixed
    */

    public function handle()
    {
        DB::table('users')->where('active', 0)->delete();
        $this->info('All inactive users are deleted successfully!');
    }
}

Now we have to register our new command with Artisan so that it will be available in the terminal. For this we just need to add this command class name to commands array in Kernel class that is available in app/Console/Kernel.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\CustomCommand::class,
    ];

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

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('custom:command')->daily();
    }
}

If you want to see your command description in terminal then run following command:

php artisan list

Now you can run your command to delete all inactive users.

php artisan custom:command

All inactive users are deleted successfully!

As you notice I schedule the command on daily basis but there is a number of schedule frequencies which you can assign to the tasks.

The schedule tasks hourly basis

$schedule->command('custom:command')->hourly();

If you want to start the scheduler itself then you will have to add one cronjob on the server using the crontab -e command.

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Using this, Laravel command scheduler will be called by cron every minute.

Happy Coding 😉

Leave a Reply

%d bloggers like this: