Introduction to Kue Scheduler
Kue-scheduler is a powerful and flexible job scheduling tool for Node.js, built on top of Kue. It allows developers to create, schedule, and manage jobs with ease. This guide will provide an in-depth look at kue-scheduler, explaining its APIs with coding examples to help you understand how to integrate it into your applications.
Installation
npm install kue-scheduler --save
Creating a Kue Scheduler Instance
const kue = require('kue'); const Queue = require('kue-scheduler'); const queue = Queue.createQueue();
Scheduling Jobs
Scheduling a job with kue-scheduler is straightforward. Here are some examples:
Scheduling a Job to Run Once at a Specific Time
const job = queue.createJob('myJobType', { title: 'my job' }); queue.schedule('at 03:30pm', job);
Scheduling a Recuring Job
queue.every('5 minutes', 'myRecurringJob', { title: 'my recurring job' });
Scheduling with a Crontab Syntax
queue.schedule('0 15 * * *', 'myCrontabJob', { title: 'my crontab job' });
Managing Scheduled Jobs
kue-scheduler provides several methods to manage jobs:
Checking if a Job is Scheduled
queue.scheduled('every 5 minutes', 'myRecurringJob', (err, isScheduled) => { if (isScheduled) { console.log('The job is scheduled'); } });
Removing a Scheduled Job
queue.remove('every 5 minutes', 'myRecurringJob', (err) => { if (!err) { console.log('The job has been removed'); } });
Using kue-scheduler in an Application
Below is an example of a simple Node.js application that uses kue-scheduler to handle job scheduling:
const express = require('express'); const kue = require('kue'); const Queue = require('kue-scheduler'); const queue = Queue.createQueue(); const app = express(); const jobType = 'email'; // Job processing logic queue.process(jobType, (job, done) => { sendEmail(job.data, done); }); // Function to send an email (dummy function) function sendEmail(data, done) { console.log('Sending email to:', data.email); setTimeout(() => { done(); }, 1000); } // API to schedule an email job app.post('/schedule-email', (req, res) => { const email = req.body.email; const job = queue.createJob(jobType, { email }); queue.schedule('at 10:00am', job); res.send('Email job scheduled'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
This application sets up an Express server with an endpoint to schedule jobs. When a POST request is made to /schedule-email
with an email address, it schedules an email job to be sent at 10:00am. The job is processed by the queue.process
method, which simulates sending an email.
Conclusion
kue-scheduler is a robust solution for job scheduling in Node.js. It seamlessly integrates with Kue and provides a range of APIs to create and manage jobs. By leveraging these features, you can build efficient job scheduling systems tailor-made for your application’s needs.
Hash: cc75dac2aa651140591a0045184206fbba1a136e8f8cb42a5e939a981c211527