Laravel cronjob run what's inside the method

2019-03-03 16:38发布

问题:

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)

回答1:

You can just pass the controller@method as a string to call().

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