Laravel Cronjobs
Laravel Cronjobs
app/Console/Commands/TestCron.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
info("Cron Job running at ". now());
$response = Http::get('https://jsonplaceholder.typicode.com/users');
$users = $response->json();
if (!empty($users)) {
foreach ($users as $key => $user) {
if(!User::where('email', $user['email'])->exists() ){
User::create([
'name' => $user['name'],
'email' => $user['email'],
'password' => bcrypt('123456789')
]);
}
}
}
}
}
In this step, we'll define our commands in the console.php file along with
the scheduled time for running each command. We'll use functions like ->daily(), -
>hourly(), etc.
routes/console.php
<?php
use Illuminate\Support\Facades\Schedule;
Schedule::command('test:cron')->everyFiveMinutes();
Now, we'll run the custom create command using the following laravel artisan
command.
After running, the above command you will see an output like this.
$cat storage/logs/laravel.php
To view an overview of your scheduled tasks, use the schedule:list Artisan command.
OR
In this step, we'll set up a cron job command on the server. If you're using Ubuntu
Server, crontab is likely already installed. Run the command below to add a new
entry for the cron job.
crontab -e
* * * * * cd /path-to-your-project & php artisan schedule:run >> /dev/null 2>&1