Почему работа Laravel Cron не работает на cpanel?

#php #html #laravel #command #scheduler

Вопрос:

Я пытаюсь запустить команду «Запланировать запуск» в cpanel через задание cron, но она не работает. Я использовал следующую команду:

 *   *   *   *   *   /usr/local/bin/ea-php73 /home/mozeshan/xicov/artisan schedule:run >> /dev/null 2>amp;1
 

Примечание:мои общедоступные файлы находятся в папке public_html, а остальные-в /home/mozeshan/xicov

Мой командный файл выглядит так:

 class MakeWinners extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:winners';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Make winners daily and weekly';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $date = Carbon::now()->format('Y-m-d');
        // current day
        $day = Carbon::now()->format('D');
        // check for weeekly winner
        if($day === "Mon"){
            $weekly = PurchaseTicket::whereBetween('created_at',array(CarbonCarbon::now()->startOfWeek(),CarbonCarbon::now()->endOfWeek()))->select('user_id', DB::raw('COUNT(*) AS cnt'))
            ->groupBy('user_id')
            ->orderByRaw('COUNT(*) DESC')
            ->get();
            $weeklyCriteria = WeeklyWinnerCriteria::findOrFail(1);
            $max = 0;
            // getting weekly winner
            foreach($weekly as  $k => $v){
                $max = max( array( $max, $v['cnt'] ) );
                if($max === $v->cnt){
                    $weeklyWinner = new WeeklyWinner();
                    $weeklyWinner->amount = $weeklyCriteria->amount;
                    $weeklyWinner->user_id = $v->user_id;
                    $weeklyWinner->save();
                }
            }

            // for Daily winner
            $ticketsPurchasers = PurchaseTicket::where('created_at','like',"%".$date."%")->get();
            $criteria = SelectWinner::findOrFail(1);
            $endPoint =$ticketsPurchasers->count();    
            for($i = 0; $i < $criteria->winners; $i  )
            {
                $winnerIndex =rand(0,$endPoint-1);
                $winner = $ticketsPurchasers[$winnerIndex];
                $PreviousWinner = new PreviousWinner();
                $PreviousWinner->ticket_number = $winner->ticket_number;
                $PreviousWinner->amount = $criteria->amount;
                $PreviousWinner->user_id = $winner->user_id;
                $PreviousWinner->save();
            }

        }else{

            // for daily winners if day is not monday
            // $ticketsPurchasers = PurchaseTicket::where('created_at','like',"%".$date."%")->groupBy('ticket_id')->get();
    
            // foreach($ticketsPurchasers as $ticketsPurchaser){
            //     $criteria = Ticket::findOrFail($ticketsPurchaser->ticket_id);
            //     $purchased = PurchaseTicket::whereDate('created_at',$date)->where('ticket_id',$ticketsPurchaser->ticket_id)->get();
            //     for($i = 0; $i < $criteria->winner; $i  ){
            //         $endPoint =$purchased->count();
            //         $winnerIndex =rand(0,$endPoint-1);
            //         $winner = $purchased[$winnerIndex];
            //         $PreviousWinner = new PreviousWinner();
            //         $PreviousWinner->ticket_number = $winner->ticket_number;
            //         $PreviousWinner->amount = $criteria->amount;
            //         $PreviousWinner->user_id = $winner->user_id;
            //         $PreviousWinner->save();
            //     }
            // }

            $ticketsPurchasers = PurchaseTicket::where('created_at','like',"%".$date."%")->get();
            $criteria = SelectWinner::findOrFail(1);
            $endPoint =$ticketsPurchasers->count();    
            for($i = 0; $i < $criteria->winners; $i  )
            {
                $winnerIndex =rand(0,$endPoint-1);
                $winner = $ticketsPurchasers[$winnerIndex];
                $PreviousWinner = new PreviousWinner();
                $PreviousWinner->ticket_number = $winner->ticket_number;
                $PreviousWinner->amount = $criteria->amount;
                $PreviousWinner->user_id = $winner->user_id;
                $PreviousWinner->save();
            }
            
        }
    }
}
 

И в Kernel.php:

 class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
        CommandsMakeWinners::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  IlluminateConsoleSchedulingSchedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('make:winners')->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
 

Заранее спасибо.

Ответ №1:

  1. Убедитесь, что ваша команда зарегистрирована app/Console/Kernel.php
     protected $commands = [
        MakeWinners::class,
    ];
 

Вы должны проконсультироваться со своим хостинг-провайдером и спросить их о добавлении совместной работы, поскольку процесс может немного отличаться.

Вот что говорит моя панель управления:

 General example:
/usr/local/bin/php /home/thinkpro/public_html/path/to/cron/script

Domain-specific example:
/usr/local/bin/ea-php99 /home/thinkpro/domain_path/path/to/cron/script
In the above example, replace “ea-php99” with the PHP version assigned to the domain you wish to use. Look in the MultiPHP Manager for the actual PHP version assigned to a domain.
 

Вот что сказал мой хостинг — провайдер в запросе на поддержку:

 As my colleague, Rohan suggested that it might not be possible to run php artisan commands via cron jobs because the environment variables are different for the cron scheduler.

However, if you are looking for a set path then you can use the cd command combined with the cron job and give it a try.

Here is an example of a cron schedule for WordPress websites to run their self-made "wp-cron.php" script.
cd /home/your_username/public_html; php -q wp-cron.php
 

Вот пример того, как я запускаю планировщик в своей панели управления с помощью хостинга basezap. Скриншот прилагается

cd /home/thinkpro/mina.quillweb.life amp;amp; php artisan schedule:run >> /dev/null 2>amp;1

Я считаю, что вам следует попробовать следующее

* * * * * /usr/local/bin/ea-php73 /home/mozeshan/xicov amp;amp; php artisan schedule:run >> /dev/null 2>amp;1

Ответ №2:

Я решил проблему, я думаю, что проблема была с версией php. Эта команда сработала для меня:

 *   *   *   *   *   /usr/local/bin/php /home/unialso1/xicov.unialsolutions.com/artisan schedule:run