cron scheduler in laravel 4 - laravel

I am trying to set cron for a command or controller action but it seemed to be not working for me. Please see below what I have tried
I have been trying to set up scheduler as per your instructions with no result.
When I try:
1. /usr/local/bin/php /home/mysite/public_html/protected/app/start/artisan cron:run it gives error
Could not open input file: /home/mysite/public_html/protected/app/start/artisan
2. /usr/local/bin/php /home/mysite/public_html/protected/app/controllers/TestController.php
it gives error Fatal error: Class 'BaseController' not found in
3. /usr/local/bin/php -q /home/mysite/public_html/protected/app/start/artisan cron:run
Error-Could not open input file:
4. php /var/www/com/mysite.com/artisan cron:run
Status: 404 Not Found No input file specified.
/usr/local/bin/php home/opendesk/public_html/protected/app/start/artisan.php and in artisan.php I do like Artisan::add(new CronRunCommand);
Error Fatal error: Class 'Artisan' not found
/usr/local/bin/php /home/opendesk/public_html/protected/app/start/artisan.php
when in artisan.php I change it to $artisan->add(new CronRunCommand);
Error Fatal error: Call to a member function add() on a non-object
None of it seems to work. I have been read many SO and google posts but cant find a solution to this. hoping to get some help here

At first. Task Scheduling not available in laravel 4, you need use newest version.
At second. What a path /home/mysite/public_html/protected/app/start/artisan? Can you show application folder structure?
However artisan its file in application root folder in default installation. For sample - my application placed in \var\www\myaplication then artisan placed in \var\www\myaplication\artisan. And i call this php \var\www\myaplication\artisan or better, change current dir to cd \var\www\myaplication and run php artisan.
At trith artisan cron can not prepare controller method. You need create a cron task in file App\Console\Kernel
<?php
namespace App\Console;
use DB;
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::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
DB::table('recent_users')->delete();
})->daily();
}
}
For more details read documenation this very useful!

Related

How can I run in background command, which runs only in foreground?

I have the command, which works like php artisan queue:listen. And it can't work in background in common, but I have to add it to cron tab, but it does not work there. Does it possible to do something like php artisan schedule:run ? The most imortant that when I interrupt this command, all functionalyty will stop. What do I have to do in this situation?
Laravel has his own cron. First of all, you should add Laravel cron to Linux system cron
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
then you can add your commands to Laravel cron.
Laravel crons lives inside a file /app/Console/Kernel.php
the are should be inside function
protected function schedule(Schedule $schedule)
for example
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:send Taylor --force')->cron('* * * * *');
}
But if you want your command run as a system process not as a cron you should use supervisors program(supervisord) or you can create for PHP command file a systemd service file and then run as if the are a normal systemd service and even manage this service through monit program in with web interface as well
If your php script is a process it means that the constructor method of class runs only ones when you start your script and if you red db data in the constructor that data in the script would be stale
Your process script should be process something like this
class OpenOrders extends Command
{
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->initTicker();
$this->updateBalances();
//the Process
while (true) {
//this is the right place to read DB data
$this->getAllOptions();
$this->openOrders = $this->getOpenOrders();
}
return 0;
}
}

No scheduled commands are ready to run | only in $schedule

Laravel Version: 5.7.25
PHP Version: 7.2.14
Database Driver & Version: MySQL 2ยช gen. 5.7
Hi, Sorry for the trouble, I have this problem in creating a scheduled command.
Description:
In our crontab -e user we have inserted the following on Debian:
* * * * * cd /var/www/myfolder.com/ && php artisan schedule:run >> crontab.laravel
We have correctly entered the schedule function as follows:
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 = [
// 'App\Console\Commands\HelpCenter',
Commands\HelpCenter::class
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('elena:help')->everyMinute();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
but the result continues to be No scheduled commands are ready to run
we tried all the combinations impossible but nothing.
If we uncomment the function Artisan call working, the script is executed
Try to force command crontab -e
To better understand where the problem lies We have added a crontab directly with the command without going through the schedule as :
* * * * * cd /var/www/myfolder.com/ && php artisan elena:help >> crontab.laravel
This command runs perfectly every minute so we can not figure out where the problem is.
if you have the patience to give us some advice we will be happy. good day
I copy this here because this solved my issue. It's #piscator comment above.
"Did you run php artisan cache:clear? There might be a schedule file cached in your storage/framework folder."
EDIT:
This issue was giving me a lot of trouble. I'm using Laravel 5.8 and I couldn't make it work with ->withoutOverlapping(); The task will die after a while without apparent reasons and then the cron job couldn't start it again because ->withoutOverlapping() was preventing it.
Finally I found a solution here:
Basically, instead of using Laravel's ->withoutOverlapping(), you check yourself if the task is already running.
// start the queue worker, if its not running
$command = "queue:work --queue=high,email,default,low --tries=3 --delay=3";
if (!$this->osProcessIsRunning($command)) {
$schedule->command($command)->everyMinute()
->runInBackground()
->appendOutputTo(storage_path('logs/queue.log'));
}
// function for checking if the task is running
protected function osProcessIsRunning($needle)
{
// get process status. the "-ww"-option is important to get the full output!
exec('ps aux -ww', $process_status);
// search $needle in process status
$result = array_filter($process_status, function($var) use ($needle) {
return strpos($var, $needle);
});
// if the result is not empty, the needle exists in running processes
if (!empty($result)) {
return true;
}
return false;
}
Thanks to #henryonsoftware for the solution
I don't know if I am late, but I have a solution for you.
JUST ADD THE TIMEZONE IN THE SCHEDULE METHOD.
it will start working well.
Example:
$schedule->command('tenam:before')
->dailyAt('22:28')->timezone('Asia/Kolkata');

Override Laravel queue listener output [Laravel <=5.2 only]

Is there any way to somehow override the output of the queue listener?
Processed: Illuminate\Queue\CallQueuedHandler#call is not very useful, it would be nice if I could somehow output the actual jobs name, and some parameters for what is actually being processed.
Dug in the code, and WorkCommand class uses this line to output name of the job, but my actual job class is not the same job that is used here.
$this->output->writeln('<error>['.Carbon::now()->format('Y-m-d H:i:s').'] Failed:</error> '.$job->getName());
You can override the output by registering your own command with the same signature. When you call php artisan queue:work, your command will take precedence.
Just make your command inherit from Laravel's WorkCommand and override its writeOutput() method:
<?php // app/Console/Command/QueueWorkCommand.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Queue\Job;
use Illuminate\Queue\Console\WorkCommand;
class QueueWorkCommand extends WorkCommand
{
/**
* Write the status output for the queue worker.
*
* #param \Illuminate\Contracts\Queue\Job $job
* #param bool $failed
* #return void
*/
protected function writeOutput(Job $job, $failed)
{
// ...
}
}
And remember to register it with the kernel app/Console/Kernel.php.

How do I run a shell command from inside a Behat test?

I'm working on laravel 5 app and I need to create an artisan command. I'm using Behat as my testing framework. I know I can test the state of my database inside of behat. I want to run a command like"
php artisan my:command
from inside a behat step. How can I accomplish this?
Thanks
Inside your FeatureContext class:
/**
* #When I run :command
*/
public function iRun($command)
{
$this->output = shell_exec($command);
}
If you are using Symfony console component, take a look at https://gist.github.com/tPl0ch/6706427
You can even describe your commands like on https://gist.github.com/everzet/1683634.
I found a simple way to do this. Since I'm running an artisan command, I can use the Artisan facade.
/**
* #Given I run the artisan command :command with args :args
* #param $command
* #param $args
*/
public function iRunTheArtisanCommandWithArgs($command, $args)
{
\Artisan::call($command, [$args]);
}

Subclassing Migrator not working for namespaced migration

I have some namespaced migrations, and I can't get past the Class Not Found errors due to namespacing. In an earlier question, Antonio Carlos Ribeiro stated:
Laravel migrator doesn't play nice with namespaced migrations. Your best bet in this case is to subclass and substitute the Migrator class, like Christopher Pitt explains in his blog post: https://medium.com/laravel-4/6e75f99cdb0.
I have tried doing so (followed by composer dump-autoload, of course), but am continuing to receive Class Not Found errors. I've got the project files set up as
inetpub
|--appTruancy
|--database
|--2015_04_24_153942_truancy_create_districts.php
|--MigrationsServiceProvider.php
|--Migrator.php
The migration file itself is as follows:
<?php
namespace Truancy;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class TruancyCreateDistricts extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('districts', function($table) {
$table->string('id')->unique()->primary()->nullable(false);
$table->string('district');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('districts');
}
}
Migrator.php is as follows:
namespace Truancy;
use Illuminate\Database\Migrations\Migrator as Base;
class Migrator extends Base{
/**
* Resolve a migration instance from a file.
*
* #param string $file
* #return object
*/
public function resolve($file)
{
$file = implode("_", array_slice(explode("_", $file), 4));
$class = "Truancy\\" . studly_case($file);
return new $class;
}
}
MigrationServiceProvider.php is as follows:
<?php
namespace Truancy;
use Illuminate\Support\ServiceProvider;
class TruancyServiceProvider extends ServiceProvider{
public function register()
{
$this->app->bindShared(
"migrator",
function () {
return new Migrator(
$this->app->make("migration.repository"),
$this->app->make("db"),
$this->app->make("files")
);
}
);
}
}
The lines generated in autoload_classmap.php are as expected:
'Truancy\\Migrator' => $baseDir . '/appTruancy/database/migrations/Migrator.php',
'Truancy\\TruancyCreateDistricts' => $baseDir . '/appTruancy/database/migrations/2015_04_24_153942_truancy_create_districts.php',
'Truancy\\TruancyServiceProvider' => $baseDir . '/appTruancy/database/migrations/MigrationsServiceProvider.php'
I'm calling php artisan migrate --path="appTruancy/database/migrations" and I receive the error:
PHP Fatal error: Class 'TruancyCreateDistricts' not found in
C:\inetpub\laravel\vendor\laravel\framework\src\Illuminate\Database
\Migrations\Migrator.php on line 297
I know I must be doing something dumb (my instinct is $class = "Truancy\\" . studly_case($file); in Migrator.php is wrong), but I can't unscrew this lightbulb. The migrate command is obviously successfully finding my migrations file, and the correct classname is in the classmap, so it has to be somewhere in the process of resolving the classname itself from the file, which the subclass and substitution is supposed to address. Any suggestions as to where I've gone wrong?
Ok, I've gotten this working. It turns out that the Medium.com article assumes you'd just know where to put the files he talks about, which I didn't. I've made several changes, and now everything is working correctly:
I created a new appTruancy\providers subfolder, and add it to composer.json
I moved both Migrator.php and MigrationServiceProvider.php into the new folder
I changed the namespace in both of those files to Truancy\Providers to match the directory structure
I added 'Truancy\Providers\MigrationsServiceProvider' to the providers array in appTruancy\config\app.php
I added a \ in front of Schema in the migration file to reference the base namespace.
I ran dump-autoload to update the classmap
This is one of those cases where I'm not 100% certain that all of the changes were required, but the layout does make sense so I'm happy with it. So, in a nutshell, if you're trying to namespace your migrations, you need to subclass the Migrator class as described in the Medium.com article listed above, but you then need to register the service provider in config\app, making sure the class names in both files are consistent.

Resources