Running Cron tasks on Heroku for free using Heroku scheduler

Steps Involved

  1. Running Cron tasks locally using node-cron
  2. Checking the task to be executed locally
  3. Deploying the changes on the Heroku server
  4. Scheduling the task on Heroku via Heroku Scheduler

Cronjobs can be run locally via npm package — node-cron. But in Heroku, Jobs scheduled by node_cron won’t run when your free dynos are sleeping, that is if cron execution will be scheduled at the time when your server would be offline, then it won’t work. For this we use _ Heroku scheduler _ to perform Cron tasks(We can schedule a task for every _ 10 minutes _ or _ 1 hour or _ 1 day _ with the free plan). Here I am taking an example of running an API every 10 minutes._

Running Cron tasks locally using node-cron

Node-Cron is a very simple and powerful npm package from which we can easily schedule tasks of various time periods ranging from seconds to days or months. To start with it locally follow the steps →

  1. npm install cron” in the terminal
  2. Use the following code in your JavaScript file—
var CronJob = require('cron').CronJob;

var job = new CronJob('* * * * * *', function() {
console.log('You will see this message every second');
// ENTER YOUR TASK HERE
}, null, true, 'America/Los_Angeles');
job.start();

3. The asterisk denotes the time period between 2 executions. You can calculate the period using crontab

#javascript #nodejs #software-development #heroku

Scheduling Tasks on Heroku
2.10 GEEK