Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

Apply corn job in laravel project

corn expression
Real time application of corn job
How to check url status every hour using corn job
How to Update Cron Jobs from the Frontend

corn expression

The * * * * * syntax in cron represents the schedule for when the cron job should run. It uses the format:

* * * * *
| | | | |
| | | | +--- Day of the week (0 - 6) (Sunday = 0)
| | | +----- Month (1 - 12)
| | +------- Day of the month (1 - 31)
| +--------- Hour (0 - 23)
+----------- Minute (0 - 59)
Enter fullscreen mode Exit fullscreen mode

Here's an example cron job command for Laravel's scheduler:

* * * * * cd /path-to-your-laravel-project && php artisan schedule:run >> /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

Explanation:

Image description

Every 5 Minutes:

*/5 * * * *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every 5 minutes.
Every Day at 3 AM:

0 3 * * *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every day at 3:00 AM.
Every Monday at 8 PM:

0 20 * * 1
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every Monday at 8:00 PM.
Every Last Day of the Month at Midnight:

0 0 28-31 * *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job on the 28th, 29th, 30th, or 31st day of the month at midnight.
Every Weekday at Noon:

0 12 * * 1-5
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every weekday (Monday to Friday) at noon.
Every 15th Minute of the Hour:

15 * * * *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every hour at the 15th minute.
Every 2 Hours:

0 */2 * * *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every 2 hours.
Every Sunday and Wednesday at 4 AM:

0 4 * * 0,3
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job every Sunday and Wednesday at 4:00 AM.
Twice Daily at 8 AM and 8 PM:

0 8,20 * * *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job twice daily at 8:00 AM and 8:00 PM.
Once a Year on January 1st at Midnight:

0 0 1 1 *
Enter fullscreen mode Exit fullscreen mode

Explanation: This cron expression runs the job on January 1st at midnight.

Real time application of corn job

Cron jobs are widely used in Laravel applications for automating tasks that need to be executed at scheduled intervals. Here are some real-time applications of cron jobs in Laravel with examples:

Sending Scheduled Emails:

Example: Sending a weekly newsletter or a monthly report email to users.
Implementation: Use Laravel's scheduler to run a command that sends the emails at a specific time.
Data Backup:

Example: Regularly backing up the application's database to prevent data loss.
Implementation: Schedule a command to run a database backup script using a package like spatie/laravel-backup.
Cleanup Tasks:

Example: Deleting temporary files or records older than a certain period.
Implementation: Create a command that cleans up the necessary data and schedule it to run daily or weekly.
Cache Clearance:

Example: Clearing the application cache periodically to improve performance.
Implementation: Schedule a command to run Laravel's cache:clear artisan command at specific intervals.
Updating Currency Exchange Rates:

Example: Fetching and updating currency exchange rates daily.
Implementation: Schedule a command that fetches the latest rates from an API and updates the database.
Generating Reports:

Example: Generating and exporting reports for analysis.
Implementation: Create a command to generate reports based on specific criteria and schedule it to run at regular intervals.
Scheduled API Calls:

Example: Fetching data from an external API regularly.
Implementation: Schedule a command to make API requests and update the application's database with the retrieved data.
Rotating Log Files:

Example: Archiving and rotating log files to prevent them from becoming too large.
Implementation: Schedule a command that renames or archives log files based on a defined schedule.
Automated Social Media Posts:

Example: Posting updates or tweets on social media platforms at specific times.
Implementation: Schedule a command to post updates using the social media API.
Session Cleanup:

Example: Clearing expired user sessions to free up resources.
Implementation: Schedule a command to clean up expired sessions at regular intervals.
Updating Search Index:

Example: Updating the search index for search functionality.
Implementation: Schedule a command to rebuild or update the search index daily or weekly.
Automated Notifications:

Example: Sending automated notifications or reminders to users.
Implementation: Schedule a command to check for pending notifications and send them as needed.

How to check url status every hour using corn job

apply bussiness logic in controller
code checks the status of URLs stored in the Guest_post table every 24 hours. It performs a simple HTTP GET request to each URL and updates the status in the database based on the response. Any errors during the process are logged. This is useful for monitoring the reachability of URLs over time

 public function updateStatusEvery24Hours()
    {
        // Get all records from the Guest_post table
        $guestPosts = Guest_post::all();
        Log::info('Checking status for URLs: ' . json_encode($guestPosts));

        foreach ($guestPosts as $post) {
            // Check if 24 hours have passed since the last update
            $lastUpdated = Carbon::parse($post->updated_at);
            $currentTime = Carbon::now();

            // if ($currentTime->diffInMinutes($lastUpdated) >= 1) {
            // if ($currentTime->diffInHours($lastUpdated) >= 24) {
            //     // Perform the URL check (similar to your existing logic)
            //     $isUrlWorking = $this->checkIfUrlIsWorking($post->url);

            //     // Update the status in the database
            //     $post->update(['status' => $isUrlWorking]);

            //     // Log the URL and its status
            //     Log::info('URL: ' . $post->url . ', Status: ' . ($isUrlWorking ? 'Active' : 'Inactive'));
            // }

            if ($currentTime->diffInMinutes($lastUpdated) >= 1) {
                // Perform the URL check (similar to your existing logic)
                $isUrlWorking = $this->checkIfUrlIsWorking($post->url);

                // Update the status in the database
                $post->update(['status' => $isUrlWorking]);

                // Log the URL and its status
                Log::info('URL: ' . $post->url . ', Status: ' . ($isUrlWorking ? 'Active' : 'Inactive'));
            }
        }

        Log::info('Status update completed.');
    }

    protected function checkIfUrlIsWorking($url)
    {
        try {
            // Send a simple GET request and check if it's successful
            $response = Http::get($url);
            Log::info('Checking status for URL: ' . $url . ', Response: ' . $response->status());

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('Error checking URL: ' . $url . ', Error: ' . $e->getMessage());
            return false; // Error occurred, website is not reachable
        }
    }
Enter fullscreen mode Exit fullscreen mode

Step 2:- Create a command
This command essentially serves as a bridge between the Artisan command-line interface and the updateStatusEvery24Hours method defined in the GuestPostAdminController controller. It allows you to run this specific task from the command line using php artisan guestpost:update-status
Image description

php artisan make:command UpdateStatusEvery24Hours
Enter fullscreen mode Exit fullscreen mode
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\Admin\GuestPostAdminController;

class UpdateStatusEvery24Hours extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'guestpost:update-status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update status for URLs every 24 hours';

    /**
     * Execute the console command.
     *
     * @return int
     */


    public function handle()
    {
        // Create an instance of your controller
        $controller = new GuestPostAdminController;

        // Call the controller function
        $controller->updateStatusEvery24Hours();

        $this->info('Status update completed.');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3:- In your project

Image description
The code you provided is from the Kernel class in Laravel, specifically the app\Console\Kernel.php file. This class is responsible for defining the schedule of Artisan commands that will be executed automatically by Laravel's task scheduler. Let's break down the key components of this code

app\Console\Kernel.php
Enter fullscreen mode Exit fullscreen mode
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('guestpost:update-status')->daily();
        $schedule->command('guestpost:update-status')->everyMinute();

    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
Enter fullscreen mode Exit fullscreen mode

step4

  1. Open crontab -e in your linux server
  2. /opt/lampp

  3. /opt/lampp# crontab -e

command:-

* * * * * cd /opt/lampp/htdocs/wizbrand/wz-account-admin-ms && php artisan schedule:run >> /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Manually Test on Linux

php artisan bookings:update-status
Enter fullscreen mode Exit fullscreen mode

Summary

corn expression
Every 5 Minutes:
Every Day at 3 AM:
Every Monday at 8 PM
Every Last Day of the Month at Midnight:
every weekday (Monday to Friday) at noon.
every hour at the 15th minute
every 2 hours
every Sunday and Wednesday at 4:00 AM.
twice daily at 8:00 AM and 8:00 PM
on January 1st at midnight
Real time application of corn job
Sending Scheduled Emails
Data Backup
Cleanup Tasks
Cache Clearance
Updating Currency Exchange Rates
Generating Reports
Scheduled API Calls
Rotating Log Files
Automated Social Media Posts
Session Cleanup
Updating Search Index
Automated Notifications

How to Update Cron Jobs from the Frontend

Dynamic Task Scheduling in Laravel: Updating Cron Jobs from the Frontend
Introduction
In Laravel, scheduled tasks are typically defined in the app/Console/Kernel.php file using static methods like everyMinute(), hourly(), or daily(). However, in many applications, you may want to allow users to set scheduling intervals dynamically from the frontend.

For example, in a booking system, you might want to auto-cancel bookings based on a user-defined time interval instead of a fixed everyMinute() rule.

In this tutorial, we will implement dynamic task scheduling in Laravel by storing the schedule in the database and updating it via an API.

Step 1: Create a Migration for the Schedule Settings
First, create a migration to store the user-defined scheduling interval.

php artisan make:migration create_schedule_settings_table
Now, update the migration file in

database/migrations/xxxx_xx_xx_xxxxxx_create_schedule_settings_table.php:
Enter fullscreen mode Exit fullscreen mode
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void
    {
        Schema::create('schedule_settings', function (Blueprint $table) {
            $table->id();
            $table->string('command'); // Stores the command name
            $table->string('frequency')->default('everyMinute'); // Stores the schedule type
            $table->timestamps();
        });

        // Insert default schedule
        DB::table('schedule_settings')->insert([
            'command' => 'bookings:auto-cancel',
            'frequency' => 'everyMinute',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    public function down(): void
    {
        Schema::dropIfExists('schedule_settings');
    }
};
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Model for Schedule Settings
Generate a model to interact with the schedule_settings table.

php artisan make:model ScheduleSetting
Enter fullscreen mode Exit fullscreen mode

Update app/Models/ScheduleSetting.php:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ScheduleSetting extends Model
{
    use HasFactory;

    protected $fillable = ['command', 'frequency'];
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Modify the Laravel Scheduler (Kernel.php)
Now, modify app/Console/Kernel.php to fetch scheduling intervals dynamically from the database.


namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Models\ScheduleSetting;

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule): void
    {
        $scheduleSettings = ScheduleSetting::where('command', 'bookings:auto-cancel')->first();

        if ($scheduleSettings) {
            $command = $scheduleSettings->command;
            $frequency = $scheduleSettings->frequency;

            // Map string frequency to actual schedule methods
            $task = $schedule->command($command);

            if (method_exists($task, $frequency)) {
                $task->$frequency();
            } else {
                $task->everyMinute(); // Default fallback
            }
        }
    }

    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
    }
}
Enter fullscreen mode Exit fullscreen mode

How It Works
Fetches the frequency from the schedule_settings table.
Maps the string frequency (e.g., hourly, daily, everyFiveMinutes) to a real Laravel scheduling method.
If the method exists, it is applied dynamically.
Defaults to everyMinute() if no valid frequency is found.
Step 4: Create an API to Update the Schedule
To allow the frontend to update the schedule, create a controller.

php artisan make:controller ScheduleController
Update app/Http/Controllers/ScheduleController.php:
Enter fullscreen mode Exit fullscreen mode
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ScheduleSetting;

class ScheduleController extends Controller
{
    public function updateSchedule(Request $request)
    {
        $request->validate([
            'frequency' => 'required|string|in:everyMinute,everyFiveMinutes,everyTenMinutes,hourly,daily',
        ]);

        // Update the schedule in the database
        $schedule = ScheduleSetting::where('command', 'bookings:auto-cancel')->first();
        if ($schedule) {
            $schedule->update(['frequency' => $request->frequency]);
        }

        return response()->json(['message' => 'Schedule updated successfully!']);
    }

    public function getSchedule()
    {
        $schedule = ScheduleSetting::where('command', 'bookings:auto-cancel')->first();
        return response()->json($schedule);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Define API Routes
Add API routes in routes/api.php:

use App\Http\Controllers\ScheduleController;

Route::get('/schedule', [ScheduleController::class, 'getSchedule']);
Route::post('/schedule/update', [ScheduleController::class, 'updateSchedule']);
Enter fullscreen mode Exit fullscreen mode

Step 6: Connect Frontend to API
Frontend Example (JavaScript)
Here’s how you can update the schedule from the frontend using fetch() or Axios.

Get Current Schedule

fetch("http://your-laravel-app.test/api/schedule")
  .then(response => response.json())
  .then(data => console.log("Current schedule:", data));
Enter fullscreen mode Exit fullscreen mode

Update Schedule

fetch("http://your-laravel-app.test/api/schedule/update", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    frequency: "hourly", // Change to any valid option
  }),
})
  .then(response => response.json())
  .then(data => console.log(data.message))
  .catch(error => console.error("Error updating schedule:", error));
Enter fullscreen mode Exit fullscreen mode

Step 7: Running the Scheduler
Now, run the Laravel scheduler with:

php artisan schedule:work
Enter fullscreen mode Exit fullscreen mode

This will execute commands based on the dynamically updated schedule.

Step 8: Testing the System

php artisan schedule:list
Enter fullscreen mode Exit fullscreen mode

It should show bookings:auto-cancel running everyMinute.

Step 9: Set Up the System Cron Job
Even though we've defined our Laravel schedule dynamically, the Laravel scheduler itself must run every minute for it to check and execute commands as needed.

Open Crontab
Run the following command on your server to edit the crontab:

crontab -e
Enter fullscreen mode Exit fullscreen mode

Add Laravel Scheduler to Crontab
Add this line at the end of the crontab file:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

Replace /path-to-your-project/ with the actual directory of your Laravel project.

Save and Exit

Press CTRL + X to exit.
Press Y to save changes.
Press Enter to confirm.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)