Search code examples
phplaravelcronlaravel-5.3scheduling

How can I do cron job with Queue Worker? (laravel 5.3)


I read here : https://laravel.com/docs/5.3/queues#running-the-queue-worker

I wanted to create a cron job using the tutorial, but I am confused how to implement it

My case is like this :

For example, I have table order. Table order has fields like this :

  1. The status, int (10)

  2. checkout_at, datetime

  3. canceled_at, datetime

I only mention a few field

note:

status = 1 -> Received

status = 2 -> Canceled

status = 3 -> Waitng For Payment

I want to make logic like this:

If the buyer did not paid the order in 2 hour after checkout_at, change the status to "canceled" and insert value "canceled_at"

I create a function like this :

public function cron_job()
{
    $users = DB::table('orders')
               ->select('*')
               ->first();

    $checkout_at = $users->checkout_at;
    $after = strtotime("+2 hours", strtotime($checkout_at));

    if($checkout_at > $after) {
        DB::table('orders')
          ->where('id', $users->id)
          ->update(['status ' => 2, 'canceled_at' => date("Y-m-d H:i:s")]);
    }
}

How do I create a cron job to call the function by implementing the above tutorial?


Solution

  • For this kind of job, you should use the Laravel Task Sheduling. This gives the option to execute a script every hour (or any other interval you choose).

    $schedule->call(function () {
        // Your code
    })->hourly();
    

    However, you need to be able to add a cron job on the server where your website is hosted.