Laravel 9的设置调度程序 / Cron 9
我在幼虫中做我的第一个cr。 我使用Laravel 9。 我需要通过Cron自动运行我的应用程序。
我使用调度程序(使用幼虫良好实践)在Laravel中尝试了它。
我有此代码:
命令:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
//API pogodowe
use Cmfcmf\OpenWeatherMap;
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
//dostęp do pamięci cache
use Illuminate\Support\Facades\Cache;
//biblioteka narzędzi date/time
use Illuminate\Support\Carbon;
class getWeather extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'getWeather:current'; //tak będzie wywoływana komenda z CLI (artisan command)
/**
* The console command description.
*
* @var string
*/
protected $description = 'Pobiera bieżące dane pogodowe.'; //opis komendy
/**
* Create a new command instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle() {
$lang = 'pl';
$units = 'metric';
//tworzymy obiekt OpenWeatherMap z naszym kluczem API
$owm = new OpenWeatherMap(config('constants.OPENWEATHER_API_KEY'));
//czy w cache są poprzednie dane? jeżeli tak, to pobieramy
$pogoda = Cache::has('pogoda') ? Cache::get('pogoda') : array();
// Stan powietrza
$data = @file_get_contents("http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/config('constants.ID_STACJI_POMIAROWEJ')"); //pobieramy dane z serera GIOS
if ($data) {
$air = json_decode($data); //poszło OK, dekodujemy do obiektu
} else { //uwaliło się, poinformujmy o tym w logu
$air = null;
echo Carbon::now() . "\t" . 'Bład pobierania danych o stanie powietrza' . PHP_EOL;
}
// Dane pogodowe
try {
$current = $owm->getWeather(config('constants.OPENWEATHER_CITY_ID'), $units, $lang); //pobieramy aktualne dane dla miasta z id=OPENWEATHER_CITY_ID
$forecast = $owm->getDailyWeatherForecast(config('constants.OPENWEATHER_CITY_ID'), $units, $lang, '', 2); //pobieramy prognozę na dwa najbliższe dni dla miasta z id=OPENWEATHER_CITY_ID
} catch (OWMException $e) { //lipa, coś się nie udało
echo Carbon::now() . "\t" . 'OpenWeatherMap exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').' . PHP_EOL;
} catch (Exception $e) { //lipa, ale poważniejsza
echo Carbon::now() . "\t" . 'General exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').' . PHP_EOL;
}
if ($current) { //mamy to! sprawdzamy aktualną pogodę
// Dzisiaj
if (@getimagesize('http:' . $current->weather->getIconURL())) { //sztuczka magiczna - sprawdzam, czy dostarczona nazwa pliku ikony jest powiązana z fizycznym plikiem
$pogoda['today'] = $current; //uff, wszytsko jest ok, zapisujemy w tablicy
}
}
if ($forecast) { //mamy to! sprawdzamy prognozę na jutro
$forecast->rewind(); //ustawiamy na dzisiaj
$forecast->next(); //ustawiamy na kolejnej pozycji (jutro)
$tommorow = $forecast->current(); //pobieramy jutrzejsze dane
// dalej to samo, co powyżej
if (@getimagesize('http:' . $tommorow->weather->getIconURL())) {
$pogoda['tommorow'] = $tommorow;
}
}
// Stan powietrza
if ($air && $air->stIndexLevel->id >= 0) { // ignorujemy dla id<0 - to oznacza brak danych
$pogoda['air'] = $air;
}
// Dane do cache
Cache::forget('pogoda'); //usuwamy poprzednie
Cache::forever('pogoda', $pogoda); //nowe zapisujemy na zawsze
}
}
app/console/kernel.php:
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
'\App\Console\Commands\getWeather', //to nasza nowa komenda
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('getWeather:current') // i od teraz chcemy, żeby
->everyThirtyMinutes() // była uruchamina co 30 minut
->appendOutputTo('/var/log/scheduled_weather.log') //a komunikaty zapisywała w pliku dziennika;
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
我想在午夜的每个星期一,周四和周六运行此代码。
我该如何使其工作?
I make my first cron in larval.
I use Laravel 9.
I need automated run my application via cron.
I tried it in Laravel using scheduler (use larval good practices).
I have this code:
Command:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
//API pogodowe
use Cmfcmf\OpenWeatherMap;
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
//dostęp do pamięci cache
use Illuminate\Support\Facades\Cache;
//biblioteka narzędzi date/time
use Illuminate\Support\Carbon;
class getWeather extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'getWeather:current'; //tak będzie wywoływana komenda z CLI (artisan command)
/**
* The console command description.
*
* @var string
*/
protected $description = 'Pobiera bieżące dane pogodowe.'; //opis komendy
/**
* Create a new command instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle() {
$lang = 'pl';
$units = 'metric';
//tworzymy obiekt OpenWeatherMap z naszym kluczem API
$owm = new OpenWeatherMap(config('constants.OPENWEATHER_API_KEY'));
//czy w cache są poprzednie dane? jeżeli tak, to pobieramy
$pogoda = Cache::has('pogoda') ? Cache::get('pogoda') : array();
// Stan powietrza
$data = @file_get_contents("http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/config('constants.ID_STACJI_POMIAROWEJ')"); //pobieramy dane z serera GIOS
if ($data) {
$air = json_decode($data); //poszło OK, dekodujemy do obiektu
} else { //uwaliło się, poinformujmy o tym w logu
$air = null;
echo Carbon::now() . "\t" . 'Bład pobierania danych o stanie powietrza' . PHP_EOL;
}
// Dane pogodowe
try {
$current = $owm->getWeather(config('constants.OPENWEATHER_CITY_ID'), $units, $lang); //pobieramy aktualne dane dla miasta z id=OPENWEATHER_CITY_ID
$forecast = $owm->getDailyWeatherForecast(config('constants.OPENWEATHER_CITY_ID'), $units, $lang, '', 2); //pobieramy prognozę na dwa najbliższe dni dla miasta z id=OPENWEATHER_CITY_ID
} catch (OWMException $e) { //lipa, coś się nie udało
echo Carbon::now() . "\t" . 'OpenWeatherMap exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').' . PHP_EOL;
} catch (Exception $e) { //lipa, ale poważniejsza
echo Carbon::now() . "\t" . 'General exception: ' . $e->getMessage() . ' (Code ' . $e->getCode() . ').' . PHP_EOL;
}
if ($current) { //mamy to! sprawdzamy aktualną pogodę
// Dzisiaj
if (@getimagesize('http:' . $current->weather->getIconURL())) { //sztuczka magiczna - sprawdzam, czy dostarczona nazwa pliku ikony jest powiązana z fizycznym plikiem
$pogoda['today'] = $current; //uff, wszytsko jest ok, zapisujemy w tablicy
}
}
if ($forecast) { //mamy to! sprawdzamy prognozę na jutro
$forecast->rewind(); //ustawiamy na dzisiaj
$forecast->next(); //ustawiamy na kolejnej pozycji (jutro)
$tommorow = $forecast->current(); //pobieramy jutrzejsze dane
// dalej to samo, co powyżej
if (@getimagesize('http:' . $tommorow->weather->getIconURL())) {
$pogoda['tommorow'] = $tommorow;
}
}
// Stan powietrza
if ($air && $air->stIndexLevel->id >= 0) { // ignorujemy dla id<0 - to oznacza brak danych
$pogoda['air'] = $air;
}
// Dane do cache
Cache::forget('pogoda'); //usuwamy poprzednie
Cache::forever('pogoda', $pogoda); //nowe zapisujemy na zawsze
}
}
and app/Console/kernel.php:
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
'\App\Console\Commands\getWeather', //to nasza nowa komenda
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('getWeather:current') // i od teraz chcemy, żeby
->everyThirtyMinutes() // była uruchamina co 30 minut
->appendOutputTo('/var/log/scheduled_weather.log') //a komunikaty zapisywała w pliku dziennika;
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
I want to run this code in: every Monday, Thursday and Saturday at midnight.
How can I make it work ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用在参数中的功能天数,数天
(周日= 0,星期一= 1,星期四= 4,星期六= 6)
您还可以附加您要执行CRON的时间。
有关更多信息,您可以在此处查看任务调度详细信息 https://lararavel.com/laravel.com/docs.com/docs/docs/ 9.x/调度
Use the function days that get in parameters an array of days
(Sundays=0, mondays=1, thursdays=4, saturdays=6)
you can also append the time at which you want to execute the cron.
For more information, you can check the task scheduling details here https://laravel.com/docs/9.x/scheduling