handle queue:work using exec in test mode - Laravel - php

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.

Related

Laravel 5.8 - execute background job from console command

My project is based on Laravel 5.8.
I have a console command which perform some heavy tasks (generating very big PDF files, sending massive emails, etc.)
I tried to move these tasks to a background processes using jobs.
Here is what I did in order to test how it works:
php artisan make:job TestJob
The job file:
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $data;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(array $data)
{
$this->data = $data;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
sleep(5);
$date = new \DateTime();
$currentDateTime = $date->format('Ymd-His');
$logFileName = "logs/testjob-$currentDateTime.log";
$content = var_export($this->data, true);
$res = Storage::disk('local')->put($logFileName, $content);
echo "[TestJob] Print to log file: $logFileName\n";
}
}
Console command file:
public function handle()
{
echo "[Console Command] Starting...\n";
$someData = [
'First name' => 'John',
'Surname' => 'Doe'
];
TestJob::dispatch($someData);
echo "[Console Command] Finished!\n";
}
On execution, this is the output:
[Console Command] Starting...
<<< delay 5 sec.
[TestJob] Print to log file: logs/testjob-20210628-114321.log
[Console Command] Finished!
The problem:
The job is executed inside the script, and not in background.
What should I do to make it run in background?
You should change your queue connection (driver) from sync to redis (or another supported queue driver). You can do it in your .env file (for example: QUEUE_CONNECTION=database).
https://laravel.com/docs/5.8/queues#driver-prerequisites

why my cron job is not working in laravel?

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

Scheduling SQL backups with laravel outside storage path

I know it's possible to schedule commands to be run with laravel and cron job, my goal is tro create a command to backup my sql databases into my home directory inside my VPS, the example I found uses laravel storage path to drop the backups but I was wondering how can I choose another file outside my laravel app folder (my user home directory for example), is it possible to do?
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class BackupDatabase extends Command
{
protected $signature = 'db:backup';
protected $description = 'Backup the database';
protected $process;
public function __construct()
{
parent::__construct();
$this->process = new Process(sprintf(
'mysqldump -u%s -p%s %s > %s',
config('database.connections.mysql.username'),
config('database.connections.mysql.password'),
config('database.connections.mysql.database'),
storage_path('backups/backup.sql')
));
}
public function handle()
{
try {
$this->process->mustRun();
$this->info('The backup has been proceed successfully.');
} catch (ProcessFailedException $exception) {
$this->error('The backup process has been failed.');
}
}
}

How can I make CRON settings without Task Scheduler in Laravel?

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.

Why my cron job laravel 5.3 not working on localhost?

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

Categories