问题
I'm using Laravel 5.4
and I like to send notifications to users on thursdays
at 8pm
Let's say I have
- User A in Tokyo
- User B in London
- User C in New York City
Questions
How should I set the CRON JOB so they all receive the notification at 8pm
in their local time?.
My server is in New York City
Code
$schedule->command('sendNotifications')->dailyAt('20:00')->thursdays()
回答1:
This Logic can't be done just with just one: $schedule->command('sendNotifications')
command and some parameters.
First step, if not already done, setup your server and add a Cron job that is calling the Laravel artisan command:
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
Option I
Second step change your schedule command to:
$schedule->command('sendNotifications')->everyFifteenMinutes();
or
$schedule->command('sendNotifications')->everyThirtyMinutes();
or
$schedule->command('sendNotifications')->hourly();
depending how exact you want to have it, because some time zones have 30 or 45 Minutes offset, see https://www.timeanddate.com/time/time-zones-interesting.html
Now if your command sendNotifications
is executed you have to build your logic there:
- Check if it is Thursday somewhere in the world, if not cancel
- Get timezones/counties where it is 20:00 at the moment, with tolerance if required
- Get all user in one of this timezones/counties and send the notification to them
Option II
Of course you can write 40+ different commands, one for each time zone,
and use the scheduler like this:
$schedule->command('sendNotifications_1')
->timezone('America/Chicago')
->thursdays()
->dailyAt('20:00');
$schedule->command('sendNotifications_2')
->timezone('Europe/London')
->thursdays()
->dailyAt('20:00');
$schedule->command('sendNotifications_3')
->timezone('Asia/Tokyo')
->thursdays()
->dailyAt('20:00');
回答2:
Well I don't know if laravel have this functionality.
But you can set cron job for every hour to check if that users current time(with time zone) is 8 AM and if we haven't sent notification to them.
And to those users, you can send the notification.
来源:https://stackoverflow.com/questions/46738539/cron-job-schedule-laravel-command-for-different-timezones-manage-users-local