NextJs Scheduler
- Install the required packages:
npm install node-schedule axios
Create a new file for the scheduler, for example,
scheduler.js
.Import the necessary modules in the scheduler file:
const schedule = require('node-schedule');
const axios = require('axios');
- Define the job function that will be executed by the scheduler:
const job = async () => {
try {
// Your logic here, for example, make an HTTP request
const response = await axios.get('https://example.com/api/data');
console.log('Data fetched:', response.data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
};
- Set up the schedule for the job using the
node-schedule
module. For example, to run the job every day at midnight:
const dailySchedule = '0 0 *'; // Cron expression for midnight
// Schedule the job
const scheduledJob = schedule.scheduleJob(dailySchedule, job);
// Log when the job is scheduled to run
console.log('Job scheduled at midnight every day.');
- Run the scheduler in your Next.js application. You can do this by importing the scheduler file in your
pages/api
directory or any other appropriate location:
// Import the scheduler
const scheduler = require('../../scheduler.js');
Now, the job will run based on the schedule you defined, and you can customize the schedule and job logic according to your requirements.