Here’s a guide for the simplest and fastest way I know to get a server to do work for you without you having to think about it. This is a complete tutorial: every step is listed in detail (including deployment to Heroku), so you won’t have to do any guesswork.
Set up the app
Build the app
Now add some boilerplate code to your newly minted index.js file:
Since we installed
node-schedule earlier, the first line imports that library. The
scheduleJob() function sets up a job that will run every minute. Right now, it doesn’t do much. You’ll replace my
console.log() with the task you need to perform.
You can test the app by running
node index.js from your terminal. You’ll see that the app logs “ping!” once every minute until you cancel with
CTRL + C.
GREAT WORK. You’ve built a node app that automates a task for you. Now let’s get it up on a server so you can set it and forget it.
Next, let’s create a
Procfile that will instruct Heroku to start up the app after it deploys:
The Procfile contains a command that will be invoked by us when deploy the app. Essentially, the Procfile will run the command
node index.js for us on the server to kick off our app.
Now let’s set up the app on Heroku and deploy our code:
Now all that remains is to spin up the app on Heroku. We’ll do this with
Heroku’s ps:scale command, shutting down the unneeded default
web process, and spinning up our
Let a few minutes pass, then make sure everything is working as expected by checking heroku’s logs:
You should see your console pings showing up in the logs:
Hear that sound? That’s the sound of a machine doing your work for you.
Yay ur done
Now it’s time to get creative! Here are a couple ways I’ve used this server-side scheduling:
- Schedule an automated Mailchimp email using the Mailchip API. I did this with my little side project http://weekjuice.com/.
- Scrape a site with request and cheerio, and send the data off to your database for consumption by your clients (I’m doing this with another little side project right now).
This setup will be useful for any task that requires consistent, date-based automation. Fire up your app and let it run, and you’ll never have to think about it.