beyondcode / laravel-websockets

Websockets for Laravel. Done right.
https://beyondco.de/docs/laravel-websockets
MIT License
5.07k stars 613 forks source link

Can I keep socket server running with laravel task scheduler? #188

Closed lotestudio closed 4 years ago

lotestudio commented 5 years ago

Is it a good idea to use laravel task scheduler to check server is running? Something like:

protected function schedule(Schedule $schedule)
{
   $schedule->command('websockets:start_if_not_running_custom_command')
   ->everyMinute();
}

And if yes, how can I check server running? Thanks in advance!

lotestudio commented 5 years ago

Handle method for my custom command:

   $host = 'host';
    $port = 6001;

    $connection = @fsockopen($host, $port);

    if (is_resource($connection))
    {
        $this->info('Websocket running!');
        fclose($connection);
    }
    else
    {
        $this->info('Port is not responding. Starting server...');
        \Illuminate\Support\Facades\Artisan::call('websockets:serve');
    }
benvilliere commented 5 years ago

You should use Supervisor to make sure the process is always running. See Laravel docs for guidance on configuration: https://laravel.com/docs/5.8/queues#supervisor-configuration

francislavoie commented 5 years ago

Using a cron for this is not the right approach. You should definitely be using a tool like supervisord or another kind of init tool. Cron/schedulers are meant for executing tasks like purging old records, sending out daily/whatever emails, triggering some scheduled backups, etc. Keeping a process running is a more specialized task and there are tools that are built specifically for that job.

mehdyebrahimi commented 1 year ago

on \App\Console\Kernel.php

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
         $schedule->command('websockets:serve')->when(function (){
             $connection = @fsockopen('*** YOUR WEBSOCKET ADDRESS ***', '6001');
             if (is_resource($connection))
             {
                 //WEBSOCKET IS RUNNING
                 fclose($connection);
                 return false;
             }
             else
             {
                //RUN WEBSOCKET
                 return true;
             }
         });
    }

AND it is important to know that schedule can not run automaticcaly there is two way to run them