Laravel 7 task scheduling with artisan console with example

When running web application, often we need some task to perform automatically like sending emails, run database query etc. This can be done by Cron, a task scheduling system in Linux operating system.

Laravel provides easy and simple task scheduling with Artisan console. The cron will call Laravel artisan console, which will perform task that you set.

In this article, we will create fresh Laravel application and set cronjoc using artisan console step by step. We will soft delete all users' record which is one month old. Follow the bellow steps to create automatic task scheduling.

Step 1: Laravel application

First of all, create fresh Laravel application with bellow command.

composer create-project laravel/laravel cronjob

Now edit .env file and put database details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cronjob
DB_USERNAME=root
DB_PASSWORD=secret

Also run the migration to generate users table.

php artisan migrate

Add some records in the users table manually or using Laravel's seed. You can check this article to generate fake data using Laravel's Faker.

Step 2: Artisan console

Now create new artisan console class using bellow command.

php artisan make:command DeleteOldUsers --command=delete:users

The above command will generate DeleteOldUsers.php with same classname file in app/Console/Commands directory. Open DeleteOldUsers.php file.

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'delete:users';

This is the signature command which will trigger the task.

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Delete users 30 days old';

This is description of what the command will do. Now register the command in app/Console/Kernel.php file. Add our classpath in the $commands array.

/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
protected $commands = [
    'App\Console\Commands\DeleteOldUsers'
];

You can check that your command is registered with the bellow artisan command.

php artisan list

Step 3: Database query

Now open DeleteOldUsers.php file and check handle() method. This is the method where we will write out database logic. We are deleting users which are 30 days old. So we will get records of users which has created_at data 30 days old and update its deleted_at column to current time.

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    User::->whereDate('created_at', '<', Carbon::now()->subDays(30))
        delete();
}

Don't forget to include bellow class in the beginning.

use App\User;
use Carbon\Carbon;

Here is the DeleteOldUsers.php file.

<?php

namespace App\Console\Commands;

use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Delete users 30 days old';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        User::->whereDate('created_at', '<', Carbon::now()->subDays(30))
               ->update([
                   'deleted_at' => Carbon::now()
               ]);
    }
}

You can manually try the query. Hit the bellow command to run the task manually.

php artisan delete:users

Step 4: Set schedule

Task scheduling can be run from the artisan console or from the crontab. For that we need to add our command in schedule() method in app/Console/Kernel.php.

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('delete:users')->daily();
}

Attach any bellow method as you want to run the command periodically. We will run command everyday, so attached daily() method.                                            

Method Description
->cron(‘* * * * * *’); Run the task on a custom Cron schedule
->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->everyTenMinutes(); Run the task every ten minutes
->everyFifteenMinutes(); Run the task every fifteen minutes
->everyThirtyMinutes(); Run the task every thirty minutes
->hourly(); Run the task every hour
->hourlyAt(17); Run the task every hour at 17 mins past the hour
->daily(); Run the task every day at midnight
->dailyAt(’13:00′); Run the task every day at 13:00
->twiceDaily(1, 13); Run the task daily at 1:00 & 13:00
->weekly(); Run the task every week
->weeklyOn(1, ‘8:00’); Run the task every week on Tuesday at 8:00
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone

At last, we have to add one line in the server crontab file. For that first open the cron file with bellow command.

crontab -e

and put the bellow line at the end of the file,

* * * * * cd /var/www/html/cronjob && php artisan schedule:run >> /dev/null 2>&1

This will execute the Laravel artisan command schedule:run. Laravel will evaluate your scheduled tasks and runs the tasks.

Conclusion

In this way, you can do anything as you need. You can send emails, delete or update records in database and many more. I hope it can help you.