简体   繁体   中英

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

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()

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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM