Laravel 5 task scheduling with cron job example

If you want to execute scheduling jobs in specific time and specific interval then you can apply cron job which is a Unix command.

We can manage a task in the server that executes scripts which helps in sending daily/weekly reports from our website.

The main use of cron job is in cleaningup the databases, sending the emails, executing the time consuming tasks etc. We can simply delete files from the database with the help of Cron Job.

Cron job will only work on unix based machines. It consists of a configuration file called Crontable which is also known as Crontab.

This Cron tab is used to manage the scheduling and consists of different cron jobs and each of the cron job is associated with a specific task.

Generate A New Command Class :

First, we will generate our own custom commands by running following commands which will generate a class in the app/Console/Commands/ directory.

php artisan make:console CustomCommand

After running this command you will get a message ‘Console command created successfully. ‘ on your terminal and then it generate a class file at app/Console/Commands/CustomCommand.php with default signature but you can assign the terminal command name by using — command option.

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

Whenever command will be executed in your terminal then handle method of command class is called so i will write a code to delete all inactive users 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 terminal. For this we just need to add this command class name to commands array in Kernerl class that is available in app/Console/Kernel.php.

app/Console/Kernel.php


Originally published at www.laravelfeed.com.