Reputation: 1557
I've been Googling aggressively but can't quite work out how I'd do it.
If I have a timezone for all my users (e.g 'Australia/Melbourne'
), and am running a cron
job every hour, is there a way to query for every user for whom it's currently 9am on a Monday?
Upvotes: 0
Views: 87
Reputation: 40663
Well first you should get all timezones in the database, then pick the one for which it's 9am:
$tzs = User::select('timezone')->distinct()->pluck('timezone');
$applicableTimezones = $tzs->filter(function ($timezone) {
$localTime = Carbon::now(new DateTimeZone($timezone));
return $localTime->hour == 9
&& $localTime->minute == 0
&& $localTime->dayOfWeek == Carbon::MONDAY;
});
$users = User::whereIn('timezone', $applicableTimezones)->get();
This does require 2 queries but if you are using an index for the timezones it will not require the database loop through all users and instead use the index.
Upvotes: 1
Reputation: 14268
What about in your cron job checking the time like this:
$mondayMorning = Carbon\Carbon::createFromFormat('D H:i', 'Mon 09:00', 'Australia/Melbourne');
if(Carbon\Carbon::now()->eq($mondayMorning))
{
// So here query all the users where the timezone is met. Because this condition should be
// satisfied only at that time.
$users = User::where('timezone', 'Australia/Melbourne')->get();
}
Upvotes: 0