DEV Community

Cover image for Cronjob Schedule: Automating Old Data Cleanup with Laravel
Remon Hasan
Remon Hasan

Posted on

Cronjob Schedule: Automating Old Data Cleanup with Laravel

For implementation check in : Github Repository

Introduction

I have faced a problem selecting a seat in a hall where the seat reserve timeout is supposed to be five minutes. Basically, any visitor can reserve his/her seat for at least five minutes. After that the seat will be available for all.

Problem

I have stored the selected seat on a reserve_seats table. Where I store all of the visitors' selected seats by their user_id. The main concern is it is needed to auto delete the seat when the five minutes will be passed.

Selected Seats in Hall Layout

Solution

Laravel has come up with a great solution of deleting the old data by managing schedule work.

1. Create a Laravel Artisan Command:
php artisan make:command ClearOldData
This will create a new command file in the app/Console/Commands directory.

2. Define the Command Logic:
Open the ClearOldData.php file in the app/Console/Commandsdirectory and define the logic for deleting old data. In this case, we'll assume you have a table named your_table_name and you want to delete records older than 5 minutes.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;

class ClearOldData extends Command
{
    protected $signature = 'clear:old-data';
    protected $description = 'Delete old data from the table.';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Calculate the date and time 5 minutes ago
        $fiveMinutesAgo = Carbon::now()->subMinutes(5);

        // Replace 'your_table_name' with the name of your table
        \DB::table('your_table_name')->where('created_at', '<', $fiveMinutesAgo)->delete();

        $this->info('Old data has been deleted.');
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Define the Task Scheduling:
Open the app/Console/Kernel.php file and define the scheduling logic. Add the following code to the schedule method in the Kernel class:

protected function schedule(Schedule $schedule)
{
    $schedule->command('clear:old-data')->everyMinute();
}

Enter fullscreen mode Exit fullscreen mode

4. Run the Scheduler:
To activate the task scheduler, you'll need to add a cron job that runs Laravel's scheduler every minute. In your server's cron file, add the following line:

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

Enter fullscreen mode Exit fullscreen mode

5. Run the Scheduler:
To manually run the scheduler, you can execute the following command:
php artisan schedule:run

Now, the clear:old-data command will run every minute and delete records older than 5 minutes from your specified table. Adjust the table name and timing as needed for your specific use case.

Top comments (0)