Step 1: Create a New Artisan Command
Run the following command to create a new custom Artisan command:
php artisan make:command CustomCronJob
This will generate a command file in app/Console/Commands/CustomCronJob.php.
Step 2: Define the Command Logic
Open the generated command file and modify the handle method:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Log;
class CustomCronJob extends Command
{
protected $signature = 'custom:cron';
protected $description = 'Execute a scheduled task';
public function handle()
{
Log::info('Cron job executed successfully.');
}
}
Step 3: Register the Command in Kernel
Open app/Console/Kernel.php and schedule the command inside the schedule method:
protected function schedule(Schedule $schedule)
{
$schedule->command('custom:cron')->everyMinute();
}
Step 4: Set Up the Cron Job
Open the server's crontab file:
crontab -e
Add the following line at the end of the file:
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
Step 5: Verify the Cron Job
Check Laravel logs or run the command manually to ensure it's working:
php artisan custom:cron
Conclusion
Now your Laravel cron job is successfully set up and will run at the defined intervals automatically.

0 Comments