"Best way" to run Laravel queue listen - laravel

Currently I'm working on a project where I queue emails to be send. However I wonder what would be the "best way" to run the queue listener. Right now I only know about the nohup way.
However, by using nohup it feels like the queue listener is no part of the application anymore. It's like using the scheduler to make your cronjobs more part of the application.
Are there any other ways to listen the queue and what would be your preference?

Here's what I wrote to achieve this:
app/Console/Commands/QueueProcessListener.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class QueueProcessListener extends Command
{
/**
* The name of the command/process we want to monitor. This string will be used both to check to see if the process
* is currently running and to spawn it (The arguments are appended to it).
*
* #var string
*/
protected $command = 'php artisan queue:listen';
/**
* The arguments to pass to the process when spawning it.
*
* #var string
*/
protected $arguments = '--tries=3';
/**
* The signature of the console command. We use the signature when running it through Artisan: php artisan $signature
*
* #var string
*/
protected $signature = 'queue-process-listener';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Monitor the queue listener process to ensure it is always running.';
/**
* Create a new command instance.
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
if (!$this->isProcessRunning($this->command)) {
$this->info("Starting queue listener.");
$this->executeShellCommand($this->command, $this->arguments, true);
} else {
$this->info("Queue listener is running.");
}
}
/**
* Execute a shell command, with the provided arguments, and optionally in the background. Commands that are not run
* in the background will return their output/response.
*
* #param $command
* #param string $arguments
* #param bool $background
* #return string
*/
public function executeShellCommand($command, $arguments = '', $background = false)
{
$command = trim($command);
if (!is_string($command) || empty($command)) {
return null;
}
$arguments = trim($arguments);
$cmd = trim($command . ' ' . $arguments) . ($background ? ' > /dev/null 2>/dev/null &' : '');
return shell_exec($cmd);
}
/**
* Check if a process is running using pgrep.
*
* #param $process
* #return bool
*/
public function isProcessRunning($process)
{
$output = $this->executeShellCommand('pgrep -f "' . $process . '"');
return !empty(trim($output));
}
}
app/Console/Kernel.php
<?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 = [
Commands\QueueProcessListener::class
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
// Schedule my process listener to run every 5 minutes.
$schedule->command('queue-process-listener')->everyFiveMinutes();
}
}

The documentation tells you exactly how to achieve this:
https://laravel.com/docs/5.3/queues#supervisor-configuration
I'm not sure what you mean by it not being "part of the application". Crons and background worker processes are a standard part of any scale server architecture. There's nothing wrong with using them.
You also should really avoid doing what Jonathon's answer suggests, which is basically writing your own supervisord in php. What if your server reboots? There are battle-tested solutions for this problem, that have been developed and supported by the linux community for a long time now--you should really use them.

Related

cron job with laravel to send emails to user

please help me i'm trying to make a cron job on my server to send email to user
i created a command like that :
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'contract:end';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send an email to user about the end of a contract';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$contracts = Contract::where('end_date', Carbon::parse(today())->toDateString())->get();
foreach ($contracts as $contract) {
Mail::to(Setting::first()->value('email'))->send(new ContractEmail($contract));
}
}
and in my kernel.php i added the following code :
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
//
Commands\ContractEnd::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('contract:end')
->everyMinute();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
and on my server i run the following command to run the cron job :
cd /archive/artisan && schedule:run >> /dev/null 2>&1
but it didn't send any email , can anyone help me as it's my first time using it ?
Because your command in your server is wrong you need to specify the correct path which will contain/home/your username/your website folder/artisan like this
/usr/local/bin/php /home/your user name which you can get in from job page/archive/artisan schedule:run 1>> /dev/null 2>&1

Laravel Scheduled queue:work not working automatically need to manual trigger

I have a very large cron job that need to be carry out, but server cannot handle it due to memory leaks, so i follow the suggestion to use laravel Queue, and because i can't always run php artisan queue:work, so i wrote a scheduled queue command that trigger every 5 minutes, but the queue not working unless i manual trigger it on server.
Here is my command for queue:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class EnsureQueueListenerIsRunning extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'queue:checkup';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Ensure that the queue listener is running.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
//
$this->startQueueListener();
if ( ! $this->isQueueListenerRunning()) {
$this->comment('Queue listener is being started.');
$pid = $this->startQueueListener();
$this->saveQueueListenerPID($pid);
}
$this->comment('Queue listener is running.');
}
/**
* Check if the queue listener is running.
*
* #return bool
*/
private function isQueueListenerRunning()
{
if ( ! $pid = $this->getLastQueueListenerPID()) {
return false;
}
$process = exec("ps -p $pid -opid=,cmd=");
//$processIsQueueListener = str_contains($process, 'queue:listen'); // 5.1
$processIsQueueListener = ! empty($process); // 5.6 - see comments
return $processIsQueueListener;
}
/**
* Get any existing queue listener PID.
*
* #return bool|string
*/
private function getLastQueueListenerPID()
{
if ( ! file_exists(__DIR__ . '/queue.pid')) {
return false;
}
return file_get_contents(__DIR__ . '/queue.pid');
}
/**
* Save the queue listener PID to a file.
*
* #param $pid
*
* #return void
*/
private function saveQueueListenerPID($pid)
{
file_put_contents(__DIR__ . '/queue.pid', $pid);
}
/**
* Start the queue listener.
*
* #return int
*/
private function startQueueListener()
{
//$command = 'php-cli ' . base_path() . '/artisan queue:listen --timeout=60 --sleep=5 --tries=3 > /dev/null & echo $!'; // 5.1
$command = 'php artisan queue:work --timeout=60 --sleep=5 --tries=3 > /dev/null & echo $!'; // 5.6 - see comments
$pid = exec($command);
return $pid;
}
}
Here is the kernel:
$schedule->command('queue:checkup')->everyFiveMinutes();
What should i do to make it work?
if you want to set the crone job to run automatically without initiating using command.**
go to your terminal: and run this command
crontab -e
This will open server crontab file, paste this code inside, save it and exit
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Run external command via Laravel Artisan Console

I'm looking to execute psexec from Laravel to execute some remote command and I'd like to use the Artisan Console to do so (for now). Ideally, I'd like to navigate to a url and the command would be issued (something i'd implement after this initial stage).
What I have so far is:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RestartSplunk extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'splunk:restart {host}';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Restart Splunk instance on given host';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$host = $this->argument('host');
$bar = $this->output->createProgressBar();
if ($this->confirm('Are you sure you\'d like to restart ' . $host )) {
$this->info('Restarting ' . $host . '...');
}
}
}
If someone has implemented this or can share some resources to accomplish this it'd me much appreciated.
I have found my answer The Process Component in Symphony.

Laravel 5.0 : Task scheduling

I am using Laravel 5.0.*, Now I want to implement cron job in my application.
I searched a lot but I get nothing, all the example and video tutorials are related to 5.1 and 5.3 even I search in laravel.com for task scheduling under 5.0 version but it showing nothing
Reference video link : video link
And after using above video reference, I am getting below error in terminal.
[2016-11-02 08:47:06] local.ERROR: exception 'InvalidArgumentException' with message 'There are no commands defined in the "cron" namespace.' in D:\harendar\htdocs\nkbuild\vendor\symfony\console\Symfony\Component\Console\Application.php:501
/app/Console/Kernel.php
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\Inspire',
'App\Console\Commands\LogDemo',
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')
->hourly();
$schedule->command('log:demo')->emailOutputTo('harendar#solutionavenues.com');
}
}
/app/Console/Commands/LogDemo.php
<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class LogDemo extends Command {
/**
* The console command name.
*
* #var string
*/
protected $name = 'log:demo';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Log Demo command.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function fire()
{
\log::info('I was here # ', \Carbon\Carbon::now());
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return [
['example', InputArgument::REQUIRED, 'An example argument.'],
];
}
/**
* Get the console command options.
*
* #return array
*/
protected function getOptions()
{
return [
['example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null],
];
}
}
Hello First you need to run command : php artisan make:console test(command name).
Then you find one test.php command created under app/Console/Commands/test.php .this looks like:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class test extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'test';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
//
}
}

Pass object to task scheduler

I'm using Laravel 5.2's task scheduler. I need to be able to pass two options to the scheduler, but I'm not sure how to do this.
Here is what I have in my Kernel.php:
protected function schedule(Schedule $schedule)
{
$schedule->command('simple_cron --first_option=10')
->everyMinute();
}
And this in my simple_cron command:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Article;
class SimpleCron extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'simple_cron';
/**
* The console command description.
*
* #var string
*/
protected $description = '';
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$firstOption = $this->option('first_option');
}
}
But this gives me the error:
The "--first_option" option does not exist.
What am I doing wrong?
According to the offical documentation the first thing is that your signature needs to have one/two placeholders for parameters:
protected $signature = 'simple_cron {p1} {p2} {--firstoption=5}';
Here we set a default value of 5 for the option firstoption. If you don't want a default value just write {--firstoption=}
To fetch those parameters in your handle method you can do it like that:
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$p1 = $this->argument('p1'); // should be 10
$p2 = $this->argument('p2'); // should be 20
$option1 = $this->option('firstoption'); // should be 99
//
}
You should then be able to call it like this:
$schedule->command('simple_cron 10 20 --firstoption=99')->daily();

Resources