Cron Job Task Scheduling In Laravel 11 Example

May 04, 2024 | Laravel 11 Laravel


Hello Dev,

In this tutorial, I'll guide you through setting up cron job task scheduling in a Laravel 11 application. But first, let's address why we use cron jobs and the benefits they offer in Laravel 11.

Setting up cron job task scheduling in Laravel 11 allows you to automate repetitive tasks, such as sending notifications, processing data, or interacting with external APIs. Cron jobs are essential for maintaining background processes that run at scheduled intervals, ensuring your application remains up-to-date and responsive without manual intervention.

Why Use Cron Jobs in Laravel 11?

Cron jobs are essential for automating repetitive tasks in web applications. In the context of Laravel 11, cron jobs enable us to schedule and execute commands or scripts at predefined intervals. Some common use cases include sending automated emails, fetching data from external APIs, updating database records, and performing maintenance tasks.

Benefits of Using Cron Jobs in Laravel 11:

1.Automation: Cron jobs automate routine tasks, reducing manual effort and ensuring consistency in task execution.
2.Efficiency: By scheduling tasks to run at specific intervals, cron jobs improve the efficiency of your application, enabling timely updates and notifications.
3.Scalability: Cron jobs help in scaling your application by handling background tasks without affecting the user experience or performance of your web server.
4.Reliability: Ensure critical tasks are executed regularly, even if the application is not actively used.

Now, let's proceed with setting up cron jobs in a Laravel 11 application:

1.Define Cron Job Command: Create a custom Artisan command to encapsulate the logic for fetching users from an API and storing them in the database.
2.Configure Task Scheduling: Define the scheduled tasks in the `app/Console/Kernel.php` file using Laravel's Task Scheduling feature. Specify the frequency at which the command should run (e.g., every minute).
3.Set Up Cron Job on the Server: Configure a cron job on your server to execute Laravel's scheduler every minute. This ensures that Laravel's scheduler runs at the specified intervals, triggering the defined tasks.

By following these steps, you'll be able to automate tasks in your Laravel 11 application using cron jobs, improving efficiency and scalability. Let's proceed with implementing this example.

Setting Up Cron Jobs in Laravel 11 Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel example-app
Read Also: Laravel 11 CRUD With Modals & Ajax Step 2: Create a Command

Generate a Command: Use Artisan to generate a new command. For example, to fetch users from an API and create new users in the database, run:

php artisan make:command FetchUsersCommand --command=fetch:users

Edit the Command: Open the generated command file in app/Console/Commands/FetchUsersCommand.php. Implement the handle method with your logic. For example:

app/Console/Commands/FetchUsersCommand.php
<?php
  
namespace App\Console\Commands;
  
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\User;
  
class FetchUsersCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
  
    /**
     * Execute the console command.
     */
    public function handle()
    {
        info("Cron Job running at == ". now());
      
        // Logic to fetch users from an API and create new users in the database
        // Example:
        $response = Http::get('https://api.example.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')
                    ]);
                }
            }
        }
        $this->info('Users fetched and created successfully.');
    }
}
Step 3: Schedule the Command

Open the Scheduler: Open the app/Console/Kernel.php file and locate the schedule method. Add the Command to the Schedule: Use the command method to schedule your command. For example, to run every minute:

->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
routes/console.php
<?php
  
use Illuminate\Support\Facades\Schedule;
  
protected function schedule(Schedule $schedule)
{
    $schedule->command('fetch:users')->everyMinute();
}
Read Also: Laravel 11 Autocomplete Search Using Select2 JS Example Step 4: Test Your Cron Job

Run the Command Manually: First, test your command manually by running php artisan fetch:users in your terminal.

Check the Logs: Monitor the logs to ensure your command runs as expected. You can view the logs in storage/logs/laravel.log.

php artisan schedule:run
storage/logs/laravel.php
[2024-04-29 03:52:01] local.INFO: Cron Job running at 2024-04-29 03:52:01  
Step 5: Laravel 11 Cron Job Setup on Server

Edit the Cron File: On your server, open the crontab file by running crontab -e.

Add the Laravel Scheduler Entry: Add the following line to run the Laravel scheduler every minute:

crontab -e
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Conclusion

By following these steps, you've set up a cron job in Laravel 11 to automate tasks such as fetching users from an API and creating new users in your database. This automation can be extended to various other tasks, making your application more efficient and reliable. Remember to adjust the scheduling and command logic according to your specific needs.

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"