I have a problem when I use
php artisan schedule:run
And that command returns
No scheduled commands are ready to run.
My server allows to call CRON above each 5 minutes.
So I think my server setting is the reason not to work schedule:run.
So I need to try CRON without Task Scheduler, and check if the CRON return correct response or not.
So please tell me how can I use CRON without Task Scheduler.
As information, I put my codes below.
These codes work correctly to send E-mail and make log when I use
php artisan command:notice_expired_date
Kernel.php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
'\App\Console\Commands\NoticeExpiredDateCommand',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('command:notice_expired_date')
->daily()
->at(config('const.OPEN_TIME.FROM'))
->appendOutputTo(storage_path('logs/schedule/notice_expired_date.log'));
}
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
ExpiredDateNotification.php
namespace App\Console\Commands;
use App\Ticket;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Notifications\ExpiredDateNotification;
class NoticeExpiredDateCommand extends Command
{
protected $signature = 'command:notice_expired_date';
protected $description = 'send email to user to notice the expired date of his tickets.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->checkBefore1Week();
Common::makeLog($this->getName());
}
protected function checkBefore1Week()
{
$from = Carbon::today()->copy()->addDays(7)->format('Y-m-d H:i:s'); //ex. 2019-03-01 00:00:00
$to = Carbon::tomorrow()->copy()->addDays(7)->subSecond()->format('Y-m-d H:i:s');
$tickets = Ticket::whereBetween('expired_date', [$from, $to])->get();
$noticing_users = [];
foreach ($tickets as $i => $ticket) {
$noticing_users[$i] = $ticket['user_id'];
}
if ($noticing_users != []):
$users = User::find($noticing_users);
foreach ($users as $user) :
$user->notify(new ExpiredDateNotification($user, $expired_date = $from));
endforeach;
endif;
}
}
Common.php
namespace App\Console\Commands;
class Common
{
public static function makeLog($command_name)
{
$param = [
'command_name' => $command_name,
];
\Log::info('command executed', $param);
}
}
I solved this by my self.
I wrote cron like this but not work.
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Now, I write cron like this and it works.
*/5 * * * * cd /{project directory} && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1
The directory of php may depend on the server.
And about I type below on the terminal.
php artisan schedule:run
The ones place of the minutes of the time is 5,
the command returns
Running scheduled command
If the ones place of the minutes of the time is except of 5, it returns
No scheduled commands are ready to run.
Related
I am having trouble externally processing jobs on the queue while in test mode using PHPUnit. I have a job that writes a message to the the log file which is dispatched when I visit a route, I thought it could work like the way it does in development where there is a terminal window listening for work with php artisan queue:work and the other running server.
Test.php
public function testBasicTest()
{
$message = "Sample message job " . date("l jS \of F Y h:i:s A");
$filename = "laravel.log";
$this->json('GET', route('test.test-try-log-job'), ['message' => $message]);
$this->assertDatabaseHas('jobs', [
'id' => 1,
]);
exec('php artisan queue:work'); // Artisan::call("queue:work");
}
Controller
class TestController extends Controller
{
public function tryLogJob(Request $request){
dispatch(new TestJob($request->message))->onQueue('default');
return response()->json(['success'=>true], Response::HTTP_OK);
}
}
Job
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function handle()
{
Log::info($this->message);
sleep(5);
}
}
when I use Artisan::call("queue:work"); the job is processed but when I use exec('php artisan queue:work');, it is not processed.
Is there a way I can get this to work? I really need to use the exec() function.
The phpunit.xml was configured to SQLite but the .env file was configured to MySQL.
During the test the job was being added to SQLite and not MySQL on which exec('php artisan queue:work'); is run.
I set the database variables in phpunit.xml to match those .env (MySQL) and the jobs are being handled correctly.
in db i have column visit_clear i want it 0 after one day so i used this code
in kernal.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
];
protected function schedule(Schedule $schedule)
{
$schedule->command('cron:update-user-not-new')->daily();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
and in command/UpdateUserNotNew.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateUserNotNew extends Command
{
protected $signature = 'cron:update-user-not-new';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$dayAgo = 1; // Days ago
$dayToCheck = \Carbon\Carbon::now()->subDays($dayAgo)->format('Y-m-d');
Customer::whereDate('visit_date', '<=', $dayToCheck)
->update([
'visit_clear' => 0
]);
}
}
i am sheduling commnd like this as u can see cron:update-user-not-new should i use crone:UpdateUserNotNew?
You need to register your command in Kernel.php like this:
protected $commands = [
'App\Console\Commands\UpdateUserNotNew',
];
You should then be able to run the command manually with php artisan cron:update-user-not-new
In order for the automatic running of the command to work, you need to add an entry to your system's task scheduler, as this is what Laravel uses to run commands on a schedule.
Assuming you are using Linux, you need to add an entry to your crontab. To do this, in a command prompt enter crontab -e, hit enter, and add this line:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Don't forget to replace /path-to-your-project with the root folder of your project
Once done editing the crontab, save and close the editor and the new entries should be installed, and your command should now run on the schedule.
All this info came from https://laravel.com/docs/7.x/scheduling so if you need more info take a look there
In kohana framework I can call controller via command line using
php5 index.php --uri=controller/method/var1/var2
Is it possible to call controller I want in Laravel 5 via cli? If yes, how to do this?
There is no way so far (not sure if there will ever be). However you can create your own Artisan Command that can do that. Create a command CallRoute using this:
php artisan make:console CallRoute
For Laravel 5.3 or greater you need to use make:command instead:
php artisan make:command CallRoute
This will generate a command class in app/Console/Commands/CallRoute.php. The contents of that class should look like this:
<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Http\Request;
class CallRoute extends Command {
protected $name = 'route:call';
protected $description = 'Call route from CLI';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$request = Request::create($this->option('uri'), 'GET');
$this->info(app()['Illuminate\Contracts\Http\Kernel']->handle($request));
}
protected function getOptions()
{
return [
['uri', null, InputOption::VALUE_REQUIRED, 'The path of the route to be called', null],
];
}
}
You then need to register the command by adding it to the $commands array in app/Console/Kernel.php:
protected $commands = [
...,
'App\Console\Commands\CallRoute',
];
You can now call any route by using this command:
php artisan route:call --uri=/route/path/with/param
Mind you, this command will return a response as it would be sent to the browser, that means it includes the HTTP headers at the top of the output.
I am using Laravel 5.0 and I am triggering controllers using this code:
$ php artisan tinker
$ $controller = app()->make('App\Http\Controllers\MyController');
$ app()->call([$controller, 'myMethodName'], []);
the last [] in the app()->call() can hold arguments such as [user_id] => 10 etc'
For Laravel 5.4:
php artisan make:command CallRoute
Then in app/Console/Commands/CallRoute.php:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
class CallRoute extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'route:call {uri}';
/**
* The console command description.
*
* #var string
*/
protected $description = 'php artsian route:call /route';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$request = Request::create($this->argument('uri'), 'GET');
$this->info(app()->make(\Illuminate\Contracts\Http\Kernel::class)->handle($request));
}
}
Then in app/Console/Kernel.php:
protected $commands = [
'App\Console\Commands\CallRoute'
];
Call like: php artisan route:call /path
Laravel 5.7
Using tinker
// URL: http://xxx.test/calendar?filter[id]=1&anotherparam=2
$cc = app()->make('App\Http\Controllers\CalendarController');
app()->call([$cc, 'getCalendarV2'], ['filter[id]'=>1, 'anotherparam' => '2']);
You can do it in this way too. First, create the command using
php artisan command:commandName
Now in the handle of the command, call the controller and trigger the method.
Eg,
public function handle(){
$controller = new ControllerName(); // make sure to import the controller
$controller->controllerMethod();
}
This will actually do the work. Hope, this helps.
DEPENDENCY INJECTION WON'T WORK
To version 8 of laravel.
First step: type command in terminal
php artisan tinker
Secound step:
$instante = new MyController(null);
Or if argument by an instance of model, then, pass name model class.
Example:
$instante = new MyController(new MyModelHere());
Press enter.
Finally, call method with $instante->myMethod() here.
See:
I am using windows.
My code on \app\Console\Kernel.php is like this:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Commands\CustomCommand::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('custom:command')
->everyMinute();
}
protected function commands()
{
require base_path('routes/console.php');
}
}
My code on \app\Console\Commands\CustomCommand.php is like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class CustomCommand extends Command
{
protected $signature = 'custom:command';
protected $description = 'test cron job to update status on table order';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$id = 1;
DB::table('orders')
->where('id', $id)
->update(['status' => 2, 'canceled_at' => date("Y-m-d H:i:s")]);
}
}
I run php artisan list to see my cron job
After find my cron job (custom:command), then I run my cron job with like this : php artisan custom:command
It's successful update status = 2. After that I change the status manually again become 1, and then I wait one minute, it does not update status again
Is there anyone can help me?
You should also set cron on your local web server to run cron jobs.
How you change the status manually?
You change it in the database?
maybe the cron is running but 'id' int the database is equal to '2' and maybe this is why you dont see any change!
If you look for a better way to check if the Cron job is working
just add Log that will wroth to the log file
public function handle()
{
Log::info('Cron job working'); // you can also print variables
$id = 1;
DB::table('orders')
->where('id', $id)
->update(['status' => 2, 'canceled_at' => date("Y-m-d H:i:s")]);
}
Don't forget to had the Log to your source:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
use Log; // Here
class CustomCommand extends Command
I'm creating a command for sending an email automatically daily.
I'm creating the command like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class SendEmail extends Command
{
protected $signature = 'emails:send';
protected $description = 'Sending emails to the users.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$data = array(
'name' => "МГ 'Константин Величков', гр. Пазарджик",
);
Mail::send('emails.test', $data, function ($message) {
$message->from('mg.kvelichkov#gmail.com', 'МГ "Константин Величков"');
$message->to('yoannam1502#gmail.com')->subject('Оценки');
});
$this->info('The emails are send successfully!');
}
}
And then register it in Kernel like this:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Commands\Inspire::class,
Commands\SendEmail::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:send')->daily();
}
}
I'm listing all artisan commands and i can see my new comand emails:send - therefore its created, but when i try to run it (php artisan emails:send) i got this:
[Swift_TransportException] Process could not be started [The system
cannot find the path specified. ]
What is the problem?
It seems Gmail is blocking sending emails or your environment blocks connection.
Go to this address to unlock your Gmail account. Also, check firewall settings on your server.