Laravel schedule works but command not working - laravel

With laravel schedule I have problem. schedule runs but command not working. here is example.I send mail from schedule on every minute and also want to run command on every minute to test it. command not working. I did't get email from command(with text "command executed").What I am doing wrong?
Please help.
Kernel.php
class Kernel extends ConsoleKernel {
protected $commands = [
'App\Console\Commands\myCustomCommand'
];
protected function schedule(Schedule $schedule) {
//this works
sendMailFunction('someone#gmail.com', 'test mail', 'schedule executed');
//this is not working
$schedule->command('command:myCustomCommand')->cron('* * * * *')
}
}
Command
class myCustomCommand extends Command {
protected $name = 'command:myCustomCommand';
protected $description = 'some description';
public function handle() {
sendMailFunction('someone#gmail.com', 'test mail', 'command executed');
}
}

in localhost :php artisan schedule:run
in host :* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
You have to see what it is
or
Introduce your controller in kernel.php

Related

Schedule to copy all id of Table A to Table B for weekly and insert a date to Table B Laravel

What I'm intending to do is to make a task scheduling for weekly, which is to copy all of id from table route_schedule and insert into table route_schedule_details as FK, which then will insert the date of the weeks. This is how the route_schedule_details schema:
Schema::create('route_scheduler_details', function (Blueprint $table) {
$table->id();
$table->dateTime('schedule_date')->nullable();
$table->unsignedBigInteger('route_scheduler_mstr_id')->nullable()->index('FK_route_scheduler_details_route_scheduler_mstr');
$table->foreign(['route_scheduler_mstr_id'], 'FK_route_scheduler_details_route_scheduler_mstr')->references(['id'])->on('route_scheduler_mstr')->onDelete('cascade');
});
I never used task scheduling before so I'm little bit under-knowledged here. Read in Laravel docs, I have to add the schedule in App/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$data = [];
$copies = RouteSchedulerMSTR::select('id')->get();
foreach($copies as $copy){
//I'm not sure what to do in here
}
})->weekly(1, '1:00');
}
Firstly, you need to create command because above your code can't test work or not :
php artisan make:command RouteSchedulerWeekly
<?php
namespace App\Console\Commands;
use App\Models\RouteSchedulerMSTR;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class RouteSchedulerWeekly extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'routeschedule:weekly';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Run route scheduler weekly';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
$copies = RouteSchedulerMSTR::select('id')->get();
foreach($copies as $copy){
DB::table('route_scheduler_details')->insert([
'data' => now(),
'route_scheduler_mstr_id' => $copy
]);
$this->info('Route scheduler inserting...');
}
$this->info('Done!');
}
}
Then you can test your code insert or not :
php artisan routeschedule:weekly
if you wanted function is correct, you can run by cronjob with 2 options
Direct run command with cron
crontab -e
and add below script to crontab file on your server:
0 1 * * 6 cd /var/www/your-project && php artisan routeschedule:weekly >> /dev/null 2>&1
You can test crontab script here
In Windows use Task Scheduler
OR
Run with schedule:run
Add your command in Kernel
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('routeschedule:weekly')->weekly(1, '1:00');
}
}
and add below script to crontab file on your server:
* * * * * cd /var/www/your-project && php artisan schedule:run >> /dev/null 2>&1
here * * * * * is every minute
Conclusion: I recommend option 1 that will run once in a week on your server. The option 2 also run once in a week your command but schedule:run running every minute

No scheduled commands are ready to run. Laravel 8

I'm trying to run command every minute with scheduler but scheduler:run prints No scheduled commands are ready to run. message. As I understand, I don't need to set cronjob if I want to test shcedulder by run command. Any suggestions how to solve this issue are appreciated
My command:
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'print:log';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Print in log';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
info('message from command');
}
Kernel.php
protected $commands = [
'App\Console\Commands\PrintLog',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('print:log')->everyMinute();
}
Can you try as?
protected $commands = [
Commands\PrintLog::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('print:log')->everyMinute();
}
You misunderstand. Read docs here.
schedule:run command is for production - you must use it with cronjob on server
schedule:work command is for local development and testing. Run this command in terminal window and wait one minute - your scheduled job will be dispatched.

How to Run Laravel Scheduler on Google Cloud

I am trying to run Laravel Scheduler in Google Cloud.
In my command, I have this
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\User;
use Carbon\Carbon;
class ChangeRole extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'command:update';
/**
* The console command description.
*
* #var string
*/
protected $description = 'This Changes Stuffs';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
//
$users = User::where('trialExpires', '<=', Carbon::now())->get();
foreach ($users as $user) {
$user->type= 'subscriber';
$user->save();
}
}
}
I have done this in my Kernel
protected $commands = [
//
'App\Console\Commands\ChangeRole',
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('command:update')
->daily();
}
In my cron.yaml file
cron:
- description: "daily job"
url: '* * * * * cd /project_id && php artisan command:update >> /dev/null 2>&1'
schedule: every 24 hours
retry_parameters:
min_backoff_seconds: 2.5
max_doublings: 5
timezone: Europe/Madrid
When I ran gcloud app deploy cron.yaml
I got this error
ERROR: (gcloud.app.deploy) An error occurred while parsing file: [C:\xampp1\newlibri\cron.yaml]
Unable to assign value '* * * * * cd /starlit-advice-260914 && php artisan command:update >> /dev/null 2>&1' to attribute 'url':
Value '* * * * * cd /starlit-advice-260914 && php artisan command:update >> /dev/null 2>&1' for url does not match expression '^(?:^/.*$)$'
in "C:\xampp1\newlibri\cron.yaml", line 3, column 8
I don't know what I did wrong.
When I run PHP artisan command:update. The scheduler work just fine. But I am unable to replicate on Google Cloud
I have been able to fix the error.
I have to set the URL to a get request in my application.
cron:
- description: "daily summary job"
url: /api/checksub
schedule: every 24 hours
retry_parameters:
min_backoff_seconds: 2.5
max_doublings: 5
timezone: Europe/Madrid
In my controller, I have this
public function checksub() {
$users = User::where('trialExpires', '<=', Carbon::now())->update(['role'=> 'subscriber']);
));
}
It doesn't need to setup Laravel Scheduler. Just call the get result of the URL
You might want to use the default implementation for these scheduler tasks. Basically what you do is setup a CRON task which runs the scheduler function every minute, and let the PHP code decide whether to run particular tasks.
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
This will run your app\Console\Kernel.php::schedule() function every minute, in which you can then define your tasks like:
// Example function which removes users older than a year.
$schedule->call(function () {
User::query()
->where('created_at', '<', Carbon::now()->subYear())
->delete();
})->hourly();
See https://laravel.com/docs/7.x/scheduling

Laravel 5.5: Want to run multiple cronjobs through kernel.php under App/Console

I want to run different cronjobs like deleting users, send coupon codes to users, send greeting to users who joined between specified dates and etc. Can I do the same by opening the App\Console\Kernel.php and write the command as below:
protected $commands = [
'\App\Console\Commands\DeleteUsers',
'\App\Console\Commands\SendCouponCode',
'\App\Console\Commands\SendGreetings',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('DeleteUsers:deleteuserscronjob')->everyMinute();
$schedule->command('SendCouponCode:sendcouponcodecronjob')->everyMinute();
$schedule->command('SendGreetings:sendgreetingscronjob')->everyMinute();
}
Also, can someone suggest how to run cronjobs by calling only the methods under controllers and not by commands, as like below?
App\Http\Controllers\MyController1#MyAction1
And,
App\Http\Controllers\MyController2#MyAction2
Using kernel.php to schedule tasks is the correct way to do it according to the Laravel framework.
However, if you want to execute a method in one of your controllers instead of creating a command for it, you can do it like so:
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
MyController::myStaticMethod();
})->daily();
}
For running a schedules task via a command:
protected $commands = [
Commands\MyCommand::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('mycommand:run')->withoutOverlapping();
}
Then in app\Console\Commands\MyCommand.php:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class MyCommand extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'mycommand:run';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Description of my command';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
// PUT YOUR TASK TO BE RUN HERE
}
}

Artisan: "Command not found"

So I try to add a Command with
php artisan command:make MailSendCommand
The file MailSendCommand.php is created.
I edited it to this:
class MailSendCommand extends Command {
protected $name = 'command:send-mail';
protected $description = 'Send mails to the users.';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$this->info('Befehl wird ausgeführt' );
}
...
In my file start/artisan.php I added
Artisan::add(new MailSendCommand);
but when I enter 'php artisan command:send-mail' it says:
Command "command:send-mail" is not defined.
It just worked on my Home PC (XAMPP) but not on my live server (PHP 5.5.15 (cgi-fcgi))
'php artisan clear:cache' and 'php artisan dump-autoload' did not help.
Go to app/Console/Kernel.php and add the class to the commands variable. It would look something like:
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
Commands\MyCustomCommand::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
}
Here i added MyCustomCommand as a valid artisan command. Check it is among available commands executing:
php artisan list
It looks as though the problem is related to your setup. You're using PHP CGI instead of CLI to run your commands which will not work.
Ensure that the code is there on your live environment and run your commands on CLI, as these are command line scripts.

Resources