Laravel Cronjobs

Reference: https://laravel.com/docs/5.8/scheduling#introduction

  • Laravel task schedule is defined in the app/Console/Kernel.php file’s schedule method.
  • Create a new Laravel project
    laravel new (project name)
  • Build a custom command.  Reference https://laravel.com/docs/7.x/artisan#introduction and https://laravel-news.com/custom-artisan-commands:
    php artisan make:command (command name)
    Example:  php artisan make:command testcrone
  • This will generate a file in app/console/commands/(command name).php unless otherwise specified.  All commands within the app/Console/Commands directory will automatically be registered with Artisan.  If other directories are used, you will need to  make additional calls to the load method to scan other directories.
  • In the (command name).php file, set $signature=’your command:name’ and add a description.
  • In function handle(), issue your command
  • Now open app/console/kernel.php
  • Add custom command class to the $commands array. For example:
    protected $commands = [
            commands\testcron::class,
        ];
  • Test that the command is working:
    php artisan (command signature)such as test:crone

    You should see the output from the command.

  • Modify the schedule function to execute the command. For example:
    $schedule->command('testcron')->everyMinute()->withoutOverlapping()

    This will execute command testcron every minute.  There are a variety of schedules you may assign to your task.  See reference document for details.

  • Now invoke the scheduler in the project directory (if artisan doesn’t work, you are in a subdirectory.  Try move up) :
    php artisan schedule:run

    This will work in Linux. For Windows, you still need to schedule it through the auto scheduler. Check out this post to proceed: http://laravel.at.jeffsbox.eu/laravel-5-scheduler-set-up-cron-on-windows