Search code examples
laravelscheduled-tasks

Automatically update all row's status column when time has exceeded from stored time Laravel (Task Scheduling)


I want to check my stored data at database for every minute if now time has exceeded 'close_at' time. So then I can change the 'status' column to be closed.

I've been thinking that I can ->get() all data from to the table and use looping to check every data's 'close_at' then change the status but that's not effective nor efficient is it?

Got any idea?


Solution

  • To build on the above answers into something more comprehensive :

    1. Make sure cron is executing Laravel's scheduler every minute :

      php8.0 /home/yourdomain.com/artisan schedule:run
      
    2. Make a new Laravel command to execute the relevant logic :

      php artisan create:command CloseJobs
      
    3. Write the necessary code in that class - in this case, retrieve all the relevant open jobs which need to be closed and close them, which we can do through mass assignment in one easy line (make sure your 'status' is added to the $fillable array on your model) :

      protected $signature = 'close:jobs';
      
      ....
      
      $jobs = Job::where('status', 'open')->where('close_at', '<', now())->update(['status' => 'closed']);
      
    4. Tell Laravel to execute that task every minute, in App\Console\Kernel.php :

      $schedule->command('close:jobs')->everyMinute();