Laravel 5 Check queue:work run on windows - php

I send email on my script with laravel queue.
I need to run php artisan queue:work on my script for run laravel queue.
I want to monitor if this php artisan queue:work failed, I run again. My solution is command like this on corn job
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule)
{
if(check queue failed)
$schedule->command("php artisan queue:work")->cron("* * * * *");
}
}
I have two question
1- what condition I should use instead of check queue failed
2- Is there any better solution?

This is what I did, following some tutorials online; it works fine and is not creating more instances
$schedule->command('queue:work --queue=high,low --tries=3')
->everyMinute()
->withoutOverlapping();
The important part is ->withoutOverlapping(), which will execute the command again if it is not running anymore. I still have to find a way to test what happens if it hangs, hopefully someone else can improve this answer

Related

laravel run failed job locally instead of pushing it back on the queue

Is it possible to run a failed job from the failed_jobs table locally for debugging?
I only found php artisan queue:retry in the docs, but this pushes the job back on the queue instead of executing it.
I would like to directly run the failed job instead.
You can add this to your FailedJobs Model:
public function retry() {
$this->queue = 'failed_jobs_'.$this->id;
$this->save();
Artisan::call('queue:retry '.$this->id);
Artisan::call('queue:work --once --queue='.$this->queue);
}
And then run/debug the job locally like this:
FailedJob::find($id)->retry();

Laravel Task Scheduling not running commands

In my app/Console/Kernel.php, I have set my code as
protected function schedule(Schedule $schedule)
{
$schedule->job(new Refresher);
}
When I run the php artisan schedule:run command, I get the No scheduled commands are ready to run. message. I'm not sure if I am missing out on anything, I have tried adding the ->everyMinute(), but it still does not work.
Your code is creating a queued job. The queue should run on its own. However if you want to start the queue on your own use the command:
php artisan queue:work --stop-when-empty
Queued job, like scheduled tasks, should have a frequency option chained after the job method. Add it to your code:
protected function schedule(Schedule $schedule)
{
$schedule->job(new Refresher)->everyMinute();
}
Note: the Refresher class must respect a specific class structure.You can find it in the Laravel docs https://laravel.com/docs/5.8/queues#class-structure ( I don't know the Laravel version you're working on so i posted the 5.8 docs. Just change the version to the one you're using in the URL)
If you need to create a simple task you can simply change the code to:
$schedule->call(new Refresher)->everyMinute();

How to process php artisan queue:listen

I am facing a serious problem in Laravel Queue system please help me to fix this issue.
Once I queue my mail by using
$mailer = Mail::to($email_to)->queue(new ContactGeneral($data));
it stores into the database and runs this command from terminal php artisan queue:listen it works fine once I close my terminal it does not listen to my queue.
For that, I set up a scheduled in kernem.php file like that which run in every minute
protected function schedule(Schedule $schedule){
$schedule->command('queue:listen')->everyMinute();
}
set this line in a cronjob and work fine
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Problem is as runs every minute run every minute it not kill the previous process and run another process in next minute it slowdown my server
Please can you let me know what is the best way to implement this
Thanks in advance
Best way is to use supervisor. Though if you are running the application in a shared hosting environment, you can process the queues once and then exit the process thus freeing up the memory by using the following command:
php artisan queue:work --once
Depending on how many queues you'll have, set the queue to run once every 1, 2 or 3 minutes to make sure the previous process has time to consume the queues and they won't interfere often. I think you can use the following command:
* * * * * cd /path-to-your-project && php artisan queue:work --once
No, you don't need to schedule this process
as long as queue:work process is running he will look at your "jobs" table and run task by task
what you need is something to make sure that the process doesn't end when you close the console, as user8555937 and Webinion said you need supervisor and its configuration file, once you run it it will run in the background and you can forget about it

Laravel "No scheduled commands are ready to run."

I've set up the following Laravel commands on the App\Console\Kernel:
protected function schedule(Schedule $schedule) {
$schedule->command('command:daily-reset')->daily();
$schedule->command('command:monthly-reset')->monthly();
}
Then, on my server, I've set up a cron job to run once per day (at 00:00).
0 0 * * * php /home/privates/public_html/staging/current/artisan schedule:run
My cron job is running successfully each night, but the logs simply say: "No scheduled commands are ready to run."
What am I doing wrong? I would expect my daily command to run each night.
Thanks!
When you run
php artisan schedule:run
in the server, where your project is stored, you could see all of your commands running with output, looking like this:
"Running scheduled command: '/usr/local/bin/php' 'artisan' cache:update > '/dev/null' 2>&1 &"
but only if the current time is the exact one, for which the command is scheduled. Otherwise you are going to see this output:
"No scheduled commands are ready to run."
For example, if you schedule the command for every five minutes and run the command in 09:07 o'clock you will see that there are no scheduled commands, but if you run it in 09:10 you will see your command running.
In this way you can just schedule your command to run every 5 min just for debugging purposes:
$schedule->command('command:daily-reset')->everyFiveMinutes();
then observe if there is any error while running and eventually fix it. By me the problem was that I haven't installed GuzzleHttp (shame), so the fix was just running this in the terminal:
composer require guzzlehttp/guzzle
I realized that the problem for me was the below chained method:
->withoutOverlapping()
Once I removed that method, my commands started running and being found by the daemon process.
I think there might be a bug with the method, but my project for now can take a bit overlapping so it's cool.
Did you try running command manually?
Run php artisan and see if your commands have registered.
If you have registered your commands you should see command:daily-reset and command:monthly-reset under the list of available artisan commands.
If you don't see them there go ahead and register your commands by adding it to commands property available in app/Console/Kernel.php.
protected $commands = [
'App\Console\Commands\YourFirstCommand',
'App\Console\Commands\YourSecondCommand'
];
Change crontab entry to
* * * * * php /home/privates/public_html/staging/current/artisan schedule:run
The Laravel scheduled commands are based in the timezone that you have configured in your app/config/app.php file (laravel 5.1):
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'America/Bogota',
So if you create a command and register it to run as a scheduled task with:
$schedule->command('command:daily-reset')->daily();
it will run every day at 00:00 OF THE TIMEZONE SPECIFIED (in this case America/Bogota)
The same thing applies if you specify a time to run the task:
$schedule->command('command:daily-reset')->daily()->at('02:30');
This will run at 02:30 am in America/Bogota local time.
NB: This is not answer for this question, but a clue for anyone debugging with php artisan schedule:run manually. Hope it saves someone a few minutes of headache.
Check if the scheduled task can run immediately. You can use the exec method for that.
<?php
//...
protected function schedule (Schedule $schedule) {
$schedule->exec("php artisan your:command");
}
The reason for this is that, you might be scheduling the task to run at a certain time and if that time isn't due yet, it will output:
No scheduled commands are ready to run.
The full answer to this question is not listed above as far as I can see. Let's assume that our schedule is as follows:
protected function schedule(Schedule $schedule)
{
$schedule
-> command('cbh:dummyCommand')
-> everyFiveMinutes()
-> appendOutputTo ('/my/logs/laravel_output.log');
}
What I've discovered is that this code doesn't set your job to run every 5 minutes. Nor does it prevent the command running again if it was run less than 5-minutes ago.
A better way to think about it is that this code sets the named command "to be runnable every time the minute-figure of the current time is 0 or 5". In other words, if I run the command-line argument: php artisan schedule:run at 11:04, then the response is:
# No scheduled commands are ready to run.
But if I run the same command at 11:00 or 11:05, then we get:
# Running scheduled command: php artisan cbh:dummyCommand >> /my/logs/laravel_output.log 2>&1
And I end up with output in my log-file.
I discovered the above when my everyFiveMinutes() schedule was creating a log in my file every 10 minutes based on the fact that my task-scheduler was running every 2 minutes.
However, this doesn't quite address your issue, given that the daily() schedule (0 0 * * *) aligns with your cron-job schedule. The only thing I can imagine is that there is some kind of misalignment with your time-zones as suggested by #Octavio Herrera. But that's difficult to say without knowing a bit more about your environment.
I had the same problem. Every command was correctly registered but I always received the “No scheduled commands are ready to run.” message. The problem was that the website was in "maintenance mode" (php artisan down command) while we were doing updates and tests.
I think that my blog will help you answer your question. Please see the below or link: Laravel Crontab
In many projects, you need use crontab (cron jobs) to execute some tasks as sending email or delete waste record in DB. With Laravel Project, you can do this easier.
Create a command in Laravel 4:
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class FirstCommand extends Command {
/**
* The console command name.
*
* #var string
*/
protected $name = 'user:active';
/**
* 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 fire()
{
echo "User Actived";
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return array(
);
}
/**
* Get the console command options.
*
* #return array
*/
protected function getOptions()
{
return array(
array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
);
}
}
Next step, you need to register the command with Laravel CLI. So easy, you open app/start/artisan.php file, and add one line as below:
Artisan::add(new FirstCommand);
You are done creating Laravel Command. To test, you could use command below:
$ php artisan user:active
User Active
The output above mean you successfully register a command.
Finally, put your command into the crontab:
crontab -e
Add line (run command every 2 minutes):
*/2 * * * * php path_to_laravel_project/artisan user:active
That’s all. Thank you for talking time to read this.
On Windows, I fixed this issue by setting the Scheduled Task to run every minute (even though I only wanted to trigger a command once per day), otherwise I always got the No scheduled commands are ready to run. message.
Since I still ran into this issue 4 years later (2019) and a different workaround worked for me, I think it is worth hinting the simple step that solved for me, which is: Use a shorter interval first.
That seems to just wake it up to handle longer intervals in some ways. I had everyFiveMinutes() and for almost 2 hours it was getting the No scheduled commands are ready to run response. I simply changed it to everyMinute() and it started running correctly. I watched it consistently for like 10 minutes or so, then changed it back to everyFiveMinutes() and it all went smoothly.
I've stuck with this problem No scheduled commands are ready to run. for an hours, but solve it easly:
Problem was with rights to folder storage.
So, i've set chmod -R 777 storage/* (i'm not sure is this is elegant way).
After that cron starts working properly.
To run the Cron Commands on the local server, follow these steps:
I know you have already mentioned the command in app/console/Kernel.php
Now open the command line, enter "crontab -e"
Edit that file and mention the below code(without quote) to keep running PHP artisan schedule:run in the background
"* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1"
Enter "crontab -l" in the command line, it will list running crons
Done !!
Now, wait for cron to process your command. Cheers!!
Reference- https://laravel.com/docs/7.x/scheduling#introduction
For whatever reason cron does not recognize the named version of your task.
So in your schedule instead of writing
$schedule->command('command:task');
you should use the path of the class, such as
$schedule->command(\App\Console\Commands\TASK::class)
...the same goes for the scheduler on Laravel Forge!
I have tried everything but finally I found a solution for this problem. Add the timestamp in the command. Below is the example for this.
$schedule->call(function(){
print("HELLO");
})->dailyAt('21:51')->timezone('Asia/Kolkata');
or
$schedule->command('tenam:before')
->dailyAt('22:28')->timezone('Asia/Kolkata');
Try
php artisan cache:clear
and then run scheduler again with
php artisan schedule:run
I was also facing same issue and it resolved my problem.

What is the best way to set up Queues for Laravel Events?

I have an event that is fired when I receive certain notifications. I want to Queue the event so that they aren't all fired at the same time but are Queued up as I receive them and then fired after the previous event completes. I want to know the best way to do this.
Edit: Just for anyone in the future, setting up the database Queue driver is very straightforward and simple. You run the php artisan queue:table and change the driver to 'database'. My problem was that my app wasn't recognizing my QUEUE_DRIVER setting in my .env file for some reason.
Laravel 5 has it's own way of dealing with queued jobs, but you can still use the options that were available in Laravel 4. I've personally been curious as to how it all works and just threw together a blank project and ran a couple of queued jobs with a little help from the docs so this may not be a full answer but I hope this helps you on your way.
First you will want to set your config to use the database queue driver, this can be done in config/queue.php or for me it was a matter of going to the .env file and doing this: QUEUE_DRIVER=database.
Then you want to set up the database table to hold the queued jobs, you can do this by running an artisan command: php artisan queue:table this will create the migration so then you need to create the table by running php artisan migrate and then you'll have your jobs table in your DB.
Following that, you'll want to set up a queued job which come in the form of Commands. For example I'll set up a job that writes some text to the log file. You can create jobs or commands using an artisan command, here's what I did to create a command: php artisan make:command WriteToLog --queued. And here's what my command class looks like after adding a little code to get it to write to the log file...
app/Commands/WriteToLog.php
use App\Commands\Command;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class WriteToLog extends Command implements SelfHandling, ShouldBeQueued {
use InteractsWithQueue, SerializesModels;
protected $secs;
/**
* Create a new command instance.
*
* #return void
*/
public function __construct($secs)
{
$this->secs = $secs;
}
/**
* Execute the command.
*
* #return void
*/
public function handle()
{
\Log::info('Writing to the log in ' . $this->secs);
}
}
After creating a command, to test it out I wrote a route in my routes file ...
app/Http/routes.php
Route::get('/', function(){
// some time to delay the job
$fiveSecs = \Carbon\Carbon::now()->addSeconds(5);
$tenSecs = \Carbon\Carbon::now()->addSeconds(10);
// adds job to queue
Queue::later($fiveSecs, new App\Commands\WriteToLog('5 secs'));
Queue::later($tenSecs, new App\Commands\WriteToLog('10 secs'));
return 'All done';
});
Before we hit the route we want to listen for any jobs in order to process them, just run php artisan queue:listen then you can go to your browser to the route, after hitting the route in my browser the console shows
$ php artisan queue:listen
Processed: Illuminate\Queue\CallQueuedHandler#call
Processed: Illuminate\Queue\CallQueuedHandler#call
And if I check my log file I see the following:
[2015-05-19 19:25:08] local.INFO: Writing to the log in 5 secs
[2015-05-19 19:25:10] local.INFO: Writing to the log in 10 secs
Not exactly 5 and 10 seconds apart but hopefully you get the idea!
For me this is really just the tip of the iceberg and queued jobs are something very powerful in laravel, I highly recommend checking out the docs here: http://laravel.com/docs/5.0/queues and here: http://laravel.com/docs/5.0/bus
You can also fire events from your queued jobs or queue an event handler, see here for more details: http://laravel.com/docs/5.0/events#queued-event-handlers
Laravel makes queues pretty straightforward, but a bit long to explain fully here. Check out these guides:
If you are using forge, it is really painless:
https://mattstauffer.co/blog/laravel-forge-adding-a-queue-worker-with-beanstalkd
If you aren't using forge, it is still pretty ok: http://fideloper.com/ubuntu-beanstalkd-and-laravel4

Categories