Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10028

How I can delay a piece of code to be executed without breaking the execution flow in laravel?

In a laravel controller I have a piece of code that I need to be executed 48hours later once I create a record in my database.

For example once I run the following code:


$model = new Model();
$model->value = true
$model->save();

Either in console or in a controller 48hours later to execute another job that further processes the created record. Using cron is not an option because it causes in my case unessesary load to my database.

Upvotes: 0

Views: 1129

Answers (1)

Marwane Ezzaze
Marwane Ezzaze

Reputation: 1057

You can use laravel queues for that, simply by delaying job dispatch by 24 hours

you start by creating the job, then in your controller you do this for example:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\ProcessModel;
use Illuminate\Http\Request;

class ModelController extends Controller
{

    public function store(Request $request)
    {
        $model = new Model();
        $model->value = true
        $model->save();

        ProcessModal::dispatch($model)
                ->delay(now()->addHours(24));
    }
}

reference: https://laravel.com/docs/8.x/queues#delayed-dispatching

Upvotes: 1

Related Questions