Skip to main content

One post tagged with "node-cron"

View All Tags

· 2 min read

Sure, here's a step-by-step guide to installing and using the node-cron package in your JavaScript project:

  1. Open your terminal and navigate to your project directory.
  2. Install the node-cron package using npm by running the following command:
    npm install node-cron
  3. In your JavaScript file, import the node-cron module:
    const cron = require('node-cron');
  4. Use the cron.schedule() function to create a new cron job. The first argument of this function is a string that specifies the schedule using the cron syntax. The second argument is a callback function that is executed when the cron job runs. Here's an example that runs a task every minute:
    cron.schedule('* * * * *', () => {
    console.log('running a task every minute');
    });
  5. Save your changes and run your JavaScript file using the Node.js runtime:
    node your-script.js
  6. You should see the message "running a task every minute" printed to the console every minute.

Note that the cron syntax can be a bit tricky to understand at first. The five asterisks in the example (* * * * *) represent the minute, hour, day of the month, month, and day of the week, respectively. In this case, each asterisk is a wildcard that matches any value, so the cron job runs every minute. You can modify the cron syntax to match more specific schedules, such as running a task every day at 4:30 PM:

cron.schedule('30 16 * * *', () => {
console.log('running a task every day at 4:30 PM');
});

In this example, 30 16 * * * means "run every day at 4:30 PM". The first two values (30 and 16) specify the minute and hour, respectively. The remaining three asterisks are wildcards that match any day of the month, any month, and any day of the week, respectively.