Sam.tuver
Sam.tuver

Reputation: 709

Laravel - How to run a function/controller every minute ? (Task Scheduling)

I have a controller method that I want to run every minute. I read the documentation for Task Scheduling but it seems to document Commands only.

Is there any way that I can use it to call a route/controller method/script every minute ?

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Acc;

class ScriptController extends Controller
{
    public function updateAcc()
    {
        $c = new Scripts\AccountA();
        $xoo = $c->getInfo();
        $z = json_decode($xoo,true);

        $data= new Acc();
        $data->price = $z["result"];
        $data->save();
    }
}

I need to use the DB facades and external classes etc...

Upvotes: 3

Views: 9162

Answers (2)

Bara&#39; ayyash
Bara&#39; ayyash

Reputation: 1925

Yes, you can write a a shell script that will make a CurlRequest to your controller, and add the shell script to a cron job. or you can use laravel commands and call the controller by a request.

why not using the code inside the controller in a command?

Upvotes: 1

Jerodev
Jerodev

Reputation: 33206

Yes, just like the documentation states, you can make a call to any function. So you can do the following:

$schedule->call(function () {
    $controller = new \App\Http\Controllers\ScriptController();
    $controller->UpdateAcc();
})->everyMinute();

However, it is very bad practice to call a controller out of its web context, you should create a facade or a job that executes the code you want.

Upvotes: 8

Related Questions