CRON JOB - Schedule Laravel command for different timezones - Manage users local time

蹲街弑〆低调 提交于 2020-06-10 07:26:10

问题


I'm using Laravel 5.4 and I like to send notifications to users on thursdays at 8pm

Let's say I have

  1. User A in Tokyo
  2. User B in London
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!