node cron npm how to use
Using the node-cron npm package in Node.js
To use the node-cron
npm package in Node.js, you can follow these steps:
Install the
node-cron
package: Use the npm command to install thenode-cron
package in your project. Open your terminal or command prompt and run the following command:npm install node-cron
Require the
node-cron
module: In your Node.js file, require thenode-cron
module using therequire
keyword. This will allow you to use the functionality provided by the package. Here's an example:javascript const cron = require('node-cron');
Define a cron job: Use the
cron.schedule
method to define a cron job. This method takes two arguments: the cron schedule pattern and the function to be executed at the scheduled time. The cron schedule pattern determines when the function should be executed. Here's an example of defining a cron job that runs every minute:javascript cron.schedule(' *', () => { console.log('This function will run every minute'); });
The cron schedule pattern consists of five fields separated by spaces, representing minute, hour, day of the month, month, and day of the week, respectively. You can use different values or wildcards () to specify the schedule. For example,
means every minute,
0
means every hour at the 0th minute, and 0 0 *
means every day at midnight.
- Start the cron job: After defining the cron job, you need to start it using the
start
method. This will begin executing the scheduled function based on the cron schedule pattern. Here's an example:javascript cron.schedule(' *', () => { console.log('This function will run every minute'); }).start();
Once the cron job is started, it will continue running until you stop it manually or your Node.js process is terminated.
That's it! You have now learned how to use the node-cron
npm package in Node.js to schedule and execute tasks at specific intervals. Feel free to explore the node-cron
documentation for more advanced usage and options.
[[1]]: https://www.npmjs.com/package/node-cron