Job Scheduling with Cron

Scott Anderson
2 min readNov 15, 2020

Last week I talked through Puppeteer and the cool things that you can do with automation. Things such as run through the path of your site and take screenshots, thus documenting the user journey. But what if I wanted to ‘automate’ and update to my database? Maybe I would like to make a call to an API to update to the most relevant information or send out an email to those in a timezone opposite of yours?

Cron is a time-based scheduler that will fit this task perfectly. There are a few other options for job scheduling as it pertains to Nodejs but Cron seems to be the most popular and it’s fairly easy to use. Currently, I’m working on a project that will need to update our PostgresDB on a weekly basis so, Cron is going to be our tool of choice.

The hardest part of creating a job is understanding the timing. Let’s say I want a job to run every Monday morning at 2:00am …

const job = new CronJob('00 00 02 * * 1', () => {
// job to run here
}
job.start();

What if timezone is relevant in your situation and you want to send your email batch to those in Sydney when it is 8:00am for them. You don’t even have to make the conversion.

const job = new CronJob('00 00 08 * * 1-5', () => {
// send emails here
}, null, true, 'Australia/Sydney');

The scheduled job is set to run at 8:00am (’00 00 08') Monday thru Friday, ignoring the day of the month and month (‘* * 1–5’). The null value refers to an onComplete function, which is a subsequent function that can be fired once the Cron job has stopped. Note, that this is not after each run, but when you specifically run job.stop(). True refers to the start option. It will specify the job to start. This is initially set to false meaning that you will need to call job.start() to make sure the job runs. The true value is the same as job.start().

Finally, the timezone. You can check Momentjs timezones to get accurate timezones, but this job will run when it is 8:00am in Sydney and there is no conversion you need to do.

Cron is easy to use and I’m very excited to be able to implement this and possibly with puppeteer to do some fun automation.

--

--

Scott Anderson

Someone has to build the computers that will one day take over the world, it might a well be me.