Issue
In laravel 7, I setup cronjobs that runs base from different users specific timezone. Here's the exact code:
foreach (User::role('admin')->get() as $user) {
/* with queue job */
$schedule->command('weekly-survey:send')->timezone($user->timezone)->weekly()->wednesdays()->at('8:00');
$schedule->command('update:surveys-completed')->timezone($user->timezone)->daily();
$schedule->command('trial:reminder')->timezone($user->timezone)->dailyAt('7:45');
$schedule->command('trial:ends')->timezone($user->timezone)->dailyAt('23:00');
$schedule->command('subscribe:customer')->timezone($user->timezone)->dailyAt('23:45');
$schedule->command('update:user-invoice')->timezone($user->timezone)->everyMinute();
$schedule->command('employees:update-status')->timezone($user->timezone)->everyMinute();
$schedule->command('subscription:update-quantity')->timezone($user->timezone)->daily();
$schedule->command('update:freeze-account')->timezone($user->timezone)->dailyAt('22:45');
$schedule->command('send:upcoming-survey-notification')->timezone($user->timezone)->weeklyOn(1, '8:00');
$schedule->command('surveys:end-soon')->timezone($user->timezone)->dailyAt('8:00');
/* end with queue job */
/* without queue */
$schedule->command('amazon:get-send-qouta')->timezone($user->timezone)->dailyAt('23:55');
$schedule->command('amazon:get-statistics')->timezone($user->timezone)->dailyAt('23:55');
$schedule->command('update:customer-success-table')->timezone($user->timezone)->everyMinute();
$schedule->command('csm:prev-month-active')->timezone($user->timezone)->lastDayOfMonth('23:59');
$schedule->command('update:monthly-earning')->timezone($user->timezone)->lastDayOfMonth('23:59');
$schedule->command('update:subscription-status')->timezone($user->timezone)->everyMinute();
$schedule->command('retrieve:past-due-subscription')->timezone($user->timezone)->dailyAt('23:59');
$user = new User();
$user->accountNotificationsSchedule($schedule);
$schedule->command('horizon:snapshot')->timezone($user->timezone)->everyFiveMinutes();
/* end without queue */
\Log::info("Cron entry successfully executed!");
}
Do this code safe to run? First I loop through all users where has admin role and then pass user time zone to each of the command. I'm sure that this code will infinitely run for as long as the server is alive. I just want to have an alternative safe approach.
Solution
Here's what I implemented and it works.
public function handle(TimezoneRepository $timezoneRepository)
{
// get user's unique timezone
$timezones = $timezoneRepository->getUniqueTimezones();
foreach ($timezones as $timezone) {
$date = Carbon::now($timezone);
// send only on Wednesday at 8:00 am
if ($date->isWednesday() && $date->hour == 8 && $date->minute == 0) {
Survey::SendSurvey();
}
}
}
Answered By - Toksti Dats Ready