Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run cron on same time in different time zones?

I have one cron which I want to run around 6:00 am in IST and same cron should also run same time 6:00 am EAT.

I am using synced-cron for running cron jobs on my meteor server.

If I have only few timezones to support I would have ran this cron 2 times a day and it would have worked but I have multiple timezones to support in future. How can I automate same thing with little effort.

like image 994
Dhaval Chaudhary Avatar asked Apr 13 '18 06:04

Dhaval Chaudhary


3 Answers

You will need to set the cron job to run every half an hour, and then look for work based on the timezone that the user is in.

So for example you need to send a daily email digest at 6am in each timezone. Let's assume that you have the events for each user in a collection of some kind.

Each user record needs to include a timezone that the user is in. When the cron job runs, you do a query to find the users that need to receive a digest that are in the timezone where it is currently 6am. Then you send the email and clear out the queued events.

like image 70
Mikkel Avatar answered Nov 07 '22 20:11

Mikkel


A cronjob can be created with an specific timezone, here is an example:
* 1 * * * TZ="America/New_York" /command > /dev/null 2>&1

like image 27
GE ownt Avatar answered Nov 07 '22 19:11

GE ownt


After some digging I realised that running cron on every half an hour was not efficient if i am supporting only few timezones. as in send mail to users in diffrent time zones at 6 am everyday.

so for such scenario i have come up with approach where cron will run only on the which ever timezones you support.

Here's meteor solution to this approach.

setting.json

{
 "tz":["timezone1", "timezone2",...]
}

I am using this fork of sync-cron. which supports cron to run in specific timezones.

In you file where you want to run cron job.

for (let timezone = 0; timezone < Meteor.settings.tz.length; timezone++) {
  SyncedCron.add({
    name: 'name of cron in timezone' + Meteor.settings.tz[timezone],
    timezone: Meteor.settings.tz[timezone],
    context: {
      timezone: Meteor.settings.tz[timezone]
    },
    schedule(parser) {
     //do whatever you want to do with times.
     return parser.text('at 06:00 am everyday');
    },
    job() {
      //context of time zone of cron
      console.log(this.timezone);
    }
  }); 
}

so this is how you will be running cron at specific time in specific time zone and performing actions based on timezone you want to support. same solution can be applied in nodejs with diffrent package.

like image 43
Dhaval Chaudhary Avatar answered Nov 07 '22 19:11

Dhaval Chaudhary