Update Automatically Status with the help schedule()

Step 1:- Add a function in controller

In my case GuestPostAdminController:-

 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
        }
    }

Step 2:- Create a command

php artisan make:command UpdateStatusEvery24Hours
<?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.');
    }
}

Step 3:- In your project

app\Console\Kernel.php

<?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');
    }
}

In local project, you can run commands after minute

php artisan schedule:run

But when you live this code then you can put the command

Open crontab -e in your linux server

/opt/lampp

/opt/lampp# crontab -e

command:-

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

Output:-

Automatically update status if url is Active or Inactive

Hopefully, It will help you…!!!!

Related Posts

Advanced DataOps Monitoring Tools for Enterprises: A Comprehensive Implementation Guide

Introduction Enterprise data environments are becoming more complex as organizations depend on cloud platforms, data lakes, data warehouses, real-time pipelines, analytics tools, and automated workflows. When one…

Read More

The Ultimate Share Market for Beginners Guide to Smart Returns

Entering the world of equity investing can feel like stepping into a foreign country where everyone speaks a different language. The flashing tickers, fast-moving financial news charts,…

Read More

Evaluating SEO Reporting Software: Must-Have Features for Modern Enterprise

Introduction Modern marketing teams, digital agencies, and e-commerce brands juggle multiple disjointed tools to manage their online footprint. Hopping between single-purpose tools for keyword tracking, asset storage,…

Read More

Platform Engineering and GitOps: Enterprise Guide to Modern Delivery

Introduction DevOps has evolved from a niche engineering practice into a boardroom priority that directly impacts customer experience, revenue, and competitiveness. Yet many enterprises still struggle to…

Read More

Platform Engineering vs DevOps: The New Cloud Architecture Shift.

Introduction Modern software engineering moves at breakneck speeds. Organizations must deploy features rapidly while maintaining total system availability. Transitioning away from legacy architectures toward modern cloud infrastructure…

Read More

The Strategic Leader’s Guide to Choosing Scalable Workflow Orchestration Tools

Introduction Modern data architecture is growing more decentralized and complex by the day. Organizations no longer pull data from a single transactional database into an isolated local…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x