Laravel: Set/mock application time globally for development - laravel

On my application, users have lists of emails they can send to. Their accounts have settings for the time of day they want emails automatically sent and the timezone they're in.
I would like to test certain scenarios on when my queues are triggered since each user's send time may differ drastically.
I'd like to globally set a fake time with carbon.
In public/index.php, I tried to set:
$time = Carbon::create('2020-09-16 00:00:00');
Carbon::setTestNow($time);
but pieces of my application are not affected.
Is there a global way to set a fake time?
Original question below:
On my application, users have lists of emails they can send to. Their accounts have settings for the time of day they want emails automatically sent and the timezone they're in.
I have a command that will trigger an event that sends email.
Inside the listener, the handle method looks like:
public function handle(ReviewRequested $event)
{
$time = Carbon::create(2020, 9, 15, 0);
Carbon::setTestNow($time);
$reviewRequest = $event->reviewRequest;
Log::info('email sending at ' . $reviewRequest->sent_at . ' and current time is ' . Carbon::now());
Mail::to($reviewRequest->customer->email)
->later($reviewRequest->sent_at, new ReviewRequestMailer($reviewRequest));
}
Note that I'm faking the time with Carbon and setting it to midnight. In this example, The emails should be sent at 9am. The logged info is as follows:
local.INFO: email sending at 2020-09-15 09:00:00 and current time is 2020-09-15 00:00:00
So the current time is 12AM and I'm queuing these up to get sent at 9AM.
As soon as I run php artisan queue:work, the pending jobs (emails) are immediately run and sent. Why is this happening? They should remain queued until 9AM.
Perhaps queuing is using system time and doesn't care about what I set in Carbon? How can I resolve this?
Edit: I forgot to mention that I'm using Redis

Check what queue driver you're using in your .env file. QUEUE_CONNECTION=sync does not allow for any delaying (sync stands for synchronous).
The quickest way to fix this would be doing the following:
change the driver to database QUEUE_CONNECTION=database
clear the cached configuration php artisan config:clear
publish the migration for the jobs table php artisan queue:table
migrate this new table php artisan migrate
After following these steps, you can now have delayed execution in your queues when you run it with php artisan queue:work

I think you should use Laravel Cron Job for this purpose. you should make a file in App/Console/Commands/YourCronJobFile.php
<?php
namespace App\Console\Commands;
use App\TestingCron;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class TestingCronJob extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'send:Mail';
/**
* The console command description.
*
* #var string
*/
protected $description = 'This command is use for test cron jobs.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
DB::table('testing_cron')->insert(['created_at' => now(),'updated_at' => now()]);
}
}
Then go to directory 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 = [
Commands\TestingCronJob::class
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('send:Mail')->dailyAt('09:00');
}
/**
* RegisterController the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
https://laravel.com/docs/7.x/scheduling

Related

Laravel notification channel to Telegram

I want to send my articles to my Telegram channel automatically by the date time I have scheduled, so I should use queue or cron job.
I have used queue, so in local development to send notifications to telegram I refresh the webpage, I don't want it like this, when deployed to production I want it to auto-send when I have scheduled.
I think the cron job will suits best for the scenario, kindly refer the task scheduling from the laravel documentation for the same : https://laravel.com/docs/9.x/scheduling
You should create a Laravel Command. Take you code from the controller and put it there.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SendTelegram extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'command:telegram';
protected $description = 'Send a Telegram channel';
public function handle()
{
/*Here your code*/
}
}
Then, add a schedule: app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('command:telegram')
->everyMinute();
}
Finally; using terminal
php artisan schedule:run
Also, you can create a schedule cron to run your command:telegram

Laravel queue config stop working after some time

Currently I have a cron running that calls a command and adds this job to my queue.
This works normally up to a point, then the job runs but doesn't add anything to the queue, so I have to log into the server and give an artisan config:clear to get everything running again.
Does anyone have an idea what it could be? I'm using forge to perform server deployments and management, my queue is using redis driver, laravel 9, horizon and octane, php 8.1, mysql
Just to be clear: my problem is not happening while running the jobs, when the job arrives in the queue the horizon is processing perfect. the biggest problem is when adding item to the queue, that when cron goes to run, all of a sudden it doesn't find the settings of which queue it should use anymore and doesn't add anything to the queue :(
Example of command running using crontab:
namespace App\Console\Commands;
use App\Jobs\MyJob;
use Illuminate\Console\Command;
class MyCommand extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'cron:myCommand';
/**
* The console command description.
*
* #var string
*/
protected $description = '';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
MyJob::dispatch()->onQueue('my_queue');
return Command::SUCCESS;
}
}

why cron job stoped in new year 2021 in laravel

every thing works fine till 31 decemeber 2020 and in new year my cron job stoped working i dont know what happend i am using spatie laravel package to take db backup an i also have one other cron job in console and command
kernal.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\UpdateUserNotNew',
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
$schedule->command('cron:update-user-not-new')->everyMinute();
$schedule->command('backup:run')->everyMinute();
$schedule->command('backup:clean')->everyMinute();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}`
my issue is resolved byhttps://stackoverflow.com/a/65890784/14913109
only my php version was not integrated with php multimanager
The problem is most likely not coming from spatie/laravel-backup package. To run Laravels cronjob you need to a have a central call in your crontab to Laravels scheduler
* * * * * cd /path-to-your-project && php artisan schedule:run
You can also check all the scheduled tasks locally by running
$ php artisan schedule:work
and if they run fine locally then there is an issue with your server, but not with Laravel.
Also always have a look at storage/logs/laravel.log if there are any errors showing up.

Laravel cron job runs in localhost but not in my shared hosting with cpanel

I've to send automated emails to members of my subscription system. When I schedule a job in my laravel project and cron job on my localhost it runs properly every minute. But when I upload the same project to my shared hosting the scheduled task doesn't run. Can anyone help me fix this issue?
My CronTab:
SHELL="/bin/bash"
* * * * * php /home/tradiet1/public_html/tradiedemo/tradiepackage/artisan schdule:run
My NotifyMembershipRenewal:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Jobs\SendMembershipRenewalNotification;
use App\AppLog;
use Carbon\Carbon;
use App\User;
class NotifyMembershipRenewal extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'notify:membership_renewal';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send notification email to users informing them their membership subscription is about to expire .';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$args = request()->server('argv');
$log = new AppLog;
$log->url = url()->current();
$log->details = "Cron started at: ".date('Y-m-d H:i:s')." in dir: ".__DIR__;
$log->details .= "\r\n".' args: '.json_encode($args);
\DB::enableQueryLog();
$now = Carbon::now();
$expiryInDays = 7;
$from = $now->addDays($expiryInDays-1)->format('Y-m-d H:i:s');
$to = $now->addDay()->format('Y-m-d H:i:s');
$users = User::with('membership')
->where('role', 3)
->whereBetween('membership_expiry', [$from, $to])
->get();
foreach($users as $key => $user)
{
dispatch(new SendMembershipRenewalNotification($user, $expiryInDays));
}
$log->details .= "\r\n Count: ".$users->count();
$log->details .= "\r\n ".json_encode(\DB::getQueryLog())."\r\n \r\n";
$log->save();
$this->info($log->details);
}
}
My Kernel.php:
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\AppLog;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$log = new AppLog;
$log->details = "Inside Kernel#schedule";
$log->save();
$schedule->command('notify:membership_renewal')
->everyMinute() // 22:00 UTC = 08:00 AEST
->appendOutputTo('./app_log.txt')
->emailOutputTo(env('APP_LOG_EMAIL'));
/*$schedule->command('inspire')
->hourly();*/
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
My Crontab for localhost:
SHELL="/bin/bash"
* * * * * php /var/www/html/is/tradiedemo/tradiepackage/artisan schedule:run
My Crontab for my live shared hosting server
SHELL="/bin/bash"
* * * * * php /home/tradiet1/public_html/tradiedemo/tradiepackage/artisan schdule:run
The cron jobs run normally on my localhost and I get email every minute and log is stored in the DB as well as file. But when I transfer the project to my server the cron job runs every minute but the scheduled task doesn't run every minute. The task doesn't run even once.
In Shared Hosting you can't run a cron job every minute. because of it's a limitation on shared hosting(In Godaddy or Hostgator I guess). so you can do like run every 30 min every 15 min.
You read it about here too Cron Job in hostgator
But ya some Hosting provider provide this facility too.
So now the question is why it's not running right.
Its happened with me too. there is some issue with register_argc_argv but sometimes setting it on also not work so best practice rather than do it with PHP.
You can do this with pho-cli that's it.
Definitely it will work.
Do it like below
SHELL="/bin/bash"
* * * * * php-cli -q /home/tradiet1/public_html/tradiedemo/tradiepackage/artisan schdule:run
Hope it works for you.
Update
So as you said it does not work for you. so there is a rough solution for this is.
why not you do a cron on URL which is quite easy and work on any shared hosting and Cpanel things.
so for this, you can use wget for url. Below is the code related to it.
wget http://example.com/check
and now on your route function run your artisan programmatically something like below.
Route::get('/check', function () {
Artisan::call('schedule:run');
});

Laravel 5.4 - schedule:run works only once

I made a custom artisan command called db:dump which dumps my database into a sql file.
I tried applying it into a scheduler so it'll backup every time depending on the time range I want to apply. In this case, I tested it with everyMinute()
Here's what my Kernel look's like.
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 = [
Commands\MySqlDump::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('db:dump')
->everyMinute();
}
/**
* Register the Closure based commands for the application.
*
* #return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
It only works once when I execute php artisan schedule:run in my command prompt. Tried waiting for 5 minutes to see if it will backup 5 times but it didn't. I tried running schedule:run repeatedly and that's when it only worked each time. Basically speaking, it dumps an sql file every time I run schedule:run.
I'm totally lost now, advanced thanks to those who can help me. :)
You need to run cronjob on control panel plan servers like Plesk or directadmin or Cpanel.
egg:visit
If you are running locally, then you should use the following.
php artisan schedule:work
When you are on a live server, you have to set the cron configuration like the following
https://laravel.com/docs/8.x/scheduling#running-the-scheduler-locally

Resources