Cron run schedule not running automatically on the server - laravel

I have this cron job code in Laravel-5.8 application:
App/Console/Commands:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Hr\HrDesignation;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Exception;
use Notification;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
class UpdateCreateDesignation extends Command
{
protected $signature = 'updatecreatedesignations';
protected $description = 'Update or Create Designation';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$client = new Client();
$res = $client->request('GET','https://api.cloudjkk.net/jkkapp/profile/all-designations', [
'query' => ['key' => 'dddddd']
])->getBody();
$clientdatas = json_decode($res->getContents(), true);
foreach($clientdatas as $clientdata)
{
if ($clientdata['job_title']) {
$designation = HrDesignation::updateOrCreate([
'designation_name' => $clientdata['job_title']
],
[
'description' => $clientdata['job_description'],
'company_id' => 1,
]);
}
}
}
}
For the schedule, I have this code in the kernel which is supposed to run by 1:00a.m. every day
kernel.php
<?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\UpdateCreateDesignation',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('updatecreatedesignations')
->dailyAt('01:00');
}
protected function commands()
{
require base_path('routes/console.php');
}
}
I observe that the cron job is not running on the server as scheduled by 01:00.
There is no error.
How do I resolve this?
Thanks

Laravel needs to run the php artisan schedule:run every minute. If the current time is 01:00, that task is executed.
So you need to:
Add a cronjob every minute * * * * *.
Go to the directory cd /path-to-your-project
Run the artisan command that will match the time php artisan schedule:run
You can test this if you add a job with ->everyMinute();
$schedule->command('increment-db-int')
->everyMinute();

You will need to make sure that you have enabled the scheduler in crontab
https://laravel.com/docs/7.x/scheduling#introduction
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Related

Laravel queue job only works when I clear browser cache?

Goal: is to dispatch job: right after user is logged in into the system.
So I have placed dispatch code in: app/Http/Middleware/RedirectIfAuthenticated.php
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param Request $request
* #param \Closure $next
* #param string|null ...$guards
*
* #return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
MyJob::dispatch(Auth::user()); // HERE I DISPATCH MY JOB
return redirect(theme()->getPageUrl(RouteServiceProvider::HOME));
}
}
return $next($request);
}
}
This is my simple job example:-
<?php
namespace App\Jobs;
use App\Models\User;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class MyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public User $user;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
try {
Log::info('JOB STARTED : ' .now());
sleep(5);
Log::info('JOB ENDED : ' .now());
} catch (Exception $exception) {
Log::info('---------------------------------------------------------------------------------------');
Log::info('****************************************');
Log::info('CLASS : ' . __CLASS__);
Log::info('METHOD : ' . __METHOD__);
Log::info('FUNCTION : ' . __FUNCTION__);
Log::info('DIRECTORY : ' . __DIR__);
Log::info('****************************************');
Log::info('EXCEPTION', [
'status' => 'error',
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTrace(),
]);
}
}
}
It doesn't work until I clear the browser cache or run in incognito mode of the browser.Also it's running only once, even if I logout and login again this job won't exceute or dispatch.
I'm running my project on aws ec2 machine and this is my supervisor config:-
[program:laravel_worker]
command=php /var/www/development/artisan queue:work
process_name=%(program_name)s_%(process_num)02d
autostart=false
autorestart=true
stopsgroup=true
user=root
numprocs=3
stderr_logfile=/var/www/development/laraqueue.err.log
stdout_logfile=/var/www/development/laraqueue.out.log
stopwaitsecs=3600
Already tried all the following commands:-
php artisan queue:clear
php artisan config:cache
php artisan optimize:cache
I don't see the problem with my code, maybe something to do with user=root in supervisor config, because my project is under Ubuntu group and Ubuntu user? I don't I'm super confused where to go.

Laravel scheduler not working when called from controller

I have created a console command that (for now) just outputs a log statement.
That command is scheduled every minute.
I have a controller endpoint (located at /scheduler/run) that performs an Artisan::call(); to the artisan schedule:run command.
Locally it works perfectly (laravel valet & nginx), on production (apache) however, nothing happens when hitting that endpoint...
I do get the reply from my controller, but the scheduler is never triggered.
My route:
Route::get('/scheduler/run', SchedulerController::class)->name('scheduler');
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Artisan;
class SchedulerController extends Controller
{
public function __invoke()
{
Artisan::call('schedule:run');
return response()->noContent();
}
}
My Kernel.php
<?php
namespace App\Console;
use App\Console\Commands\PingCommand;
use App\Console\Commands\RefreshTwikeyKey;
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 = [
PingCommand::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command(PingCommand::class)->everyMinute();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

Cron job appendOutputTo not append anything in Laravel

I have a problem in my project. I cannot append output in my cron job.
Here is my code
<?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\CronEmail'
];
protected function schedule(Schedule $schedule) {
$schedule->command('app:CronEmail')->everyMinute()->appendOutputTo(public_path("cron.log"))->emailOutputTo('my email address');
}
protected function commands() {
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
But this is not append output to my file, Also it does not send output to my email address

Laravel schedule works but command not working

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

Laravel cron not working automatically

I'm working on a project in Laravel through scotch box. I am trying to automate some things through cronjobs. The problem is that my cron does not run automatticly, but when I php artisan schedule:run it runs my task perfectly.
app/commands/sendmail.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Mail;
class sendmail extends Command {
protected $name = 'sendMail';
protected $description = 'A mail has been send ';
public function fire()
{
Mail::send([],[], function($message) {
//sendmail function that works...
});
}
}
app/console/Kernel.php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
use App\Battle;
use Carbon\Carbon;
use App\Console\Commands\Inspire;
use App\Commands\mails;
class Kernel extends ConsoleKernel
{
protected $commands = [
\App\Console\Commands\Inspire::class,
\App\Console\Commands\sendmail::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')
->everyMinute();
$schedule->command('sendMail')
->everyMinute();
}
}
crontab -e
# m h dom mon dow command
* * * * * php var/www/artisan schedule:run
The problem ended up being the use of an relative path versus absolute path.
Using the relative path defined as var/www/artisan will set the path according to present working directory. That would mean App/Console/var/www/artisan where no artisan was located.
Instead using an absolute path such as /var/www/artisan will set the directory directly to /var/www/artisan, which would be the correct location of artisan.
* * * * * php -d register_argc_argv=On /var/www/artisan schedule:run

Resources