简体   繁体   中英

Laravel cronjob run what's inside the method

In my controller i have these method where it checks for url status

public function index(){
    $url = Url::latest()->paginate();
    return UrlsResource::collection($url);
}

my UrlsResource return data like this

public function toArray($request)
{
    return [
        'id' => $this->id,
        'url' => $this->url,
        'status' => $this->status,
        'created_at' => Carbon::parse($this->created_at)->format('Y-m-d'),
     ];
}

where in the $this->status is an accessor from my model.

public function getStatusAttribute(){ 
    $handle = curl_init($this->url);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
    $response = curl_exec($handle);
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    curl_close($handle);
    $message = [
        '100' => '(100) Continue '. $this->url, 
        '101' => '(101) Switching Protocols '. $this->url, 
        '102' => '(102) Processing '. $this->url, 
     ];
    return $message[$httpCode];
}

How can I run a cronjob where in I want to run what's inside my index method?

I tried to make a command where in

class CheckUrl extends Command
{
protected $signature = 'check:url';
protected $description = 'Check url';

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

    public function handle()
    {
        $url = Url::latest()->paginate();
        UrlsResource::collection($url);
    }
}

and i tried to run it via command line

php artisan check:url

but nothing happened

it says on the documentation that add this cron entry to server

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

but i dont know exactly where to put it (im using xampp)

您可以将controller @ method作为字符串传递给call()。

$schedule->call('App\Http\Controllers\MyController@MyAction')->everyMinute();

you can call any method from your controller to the scheduler like that

$schedule->call('App\Http\Controllers\yourController@index')->everyMinute()

but you need to add your scheduler command to corntab so the task can be executed.

run in terminal

crontab -e

and past this command

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM