If you're writing a Node app, you might have tasks you want to reoccur periodically. For example, run a cleaning task every Sunday night. Or check for updated weather conditions every day at 4 pm.
A quick walkthrough on how to do that 🧵
There are some ways to solve this.
You could for example use setInterval() to repeat every X seconds. (Please don't do this 🚫)
Or you could a piece of your app being called with the UNIX-native cron, which you need to set up in every machine you're running this on.
As the name suggests, node-cron is based on cron which is widely used in the UNIX world do schedule tasks.
(2/8)
It consists of a so-called crontab file. Each line in this file represents an instruction what and when to execute and looks like this:
0 12 * * * /home/marc/task.sh
(3/8)
The syntax looks complicated but is not. The 5 numbers or * represent a piece of the time it should be executed.
Important is that the values are separated by a space. Also, note that the hours are indicated with the 24-hour system.
(4/8)
Each field can be:
- A number (e.g. 8)
- A list of numbers (e.g. 3,9,20)
- A range of numbers (e.g. 7-13)
- An asterisk (*), which means the task should run in any instance of the field
Additionally, it can have a "step" operator (/). This can be used to skip some values
(5/8)
30 10 25 12 * echo "merry christmas 🎄"
👆 means: "Run echo "merry christmas 🎄" every December 25th at 10:30am"
We can use the same syntax as `cron` uses, but within our Node.js application.
(6/8)
You first need to install node-cron 👇
npm install --save node-cron
And then schedule a job with cron.schedule
(7/8)
There you have it. The thing that needs most getting used to is the syntax. Once you got that down, scheduling tasks in Node.js takes little effort 💪
(8/8)
If you liked this thread, make sure to give me a follow in order to be notified about more of this 😃
There is a misconception in our industry that the senior developer title is earned by age or time in the company.
I disagree with that approach. Find out what I think a senior developer really is.
🧵👇
1. What a senior developer is NOT ☝️
👉 People that know everything about a programming language
👉 Know all the answers
👉 The absolute truth
(1/12)
2. Problem-solving 💡
👉 Make sure not to introduce unnecessary sources of errors
👉 Create as little friction with the existing system as possible
👉 Think of the bigger picture
👉 Have expandability/reusability in mind
👉 Make decisions about potential trade-offs