Installation
Getting Chronos up and running in your Node.js application is quick and straightforward.
Prerequisites
- Node.js: Version 14 or higher
- MongoDB: Version 4.0 or higher
- TypeScript (optional): For TypeScript projects
Install Chronos
Install Chronos via npm:
npm install chronos-jobs
Or using yarn:
yarn add chronos-jobs
MongoDB Setup
Chronos requires a MongoDB database to store job information. You have several options:
Option 1: Local MongoDB
Install MongoDB locally following the official MongoDB installation guide.
Option 2: MongoDB Cloud (Atlas)
- Create a free account at MongoDB Atlas
- Create a new cluster
- Get your connection string from the cluster dashboard
Option 3: Docker
Run MongoDB using Docker:
docker run --name mongodb -d -p 27017:27017 mongo:latest
Verify Installation
Create a simple test file to verify everything works:
// test-chronos.js
const { Chronos } = require('chronos-jobs');
const scheduler = new Chronos({
db: { address: 'mongodb://127.0.0.1:27017/test-chronos' }
});
scheduler.define('test job', async (job) => {
console.log('Test job running!', job.attrs.data);
});
(async () => {
await scheduler.start();
await scheduler.now('test job', { message: 'Hello Chronos!' });
// Wait a moment for the job to complete
setTimeout(async () => {
await scheduler.stop();
console.log('Test completed successfully!');
process.exit(0);
}, 1000);
})();
Run the test:
node test-chronos.js
You should see:
Test job running! { message: 'Hello Chronos!' }
Test completed successfully!
TypeScript Setup
If you're using TypeScript, Chronos includes built-in type definitions:
import { Chronos } from 'chronos-jobs';
const scheduler = new Chronos({
db: { address: 'mongodb://127.0.0.1:27017/scheduler' }
});
scheduler.define('typed job', async (job) => {
// Full type support
const data = job.attrs.data;
console.log('Job data:', data);
});
Environment Variables
For production applications, use environment variables for configuration:
const scheduler = new Chronos({
db: {
address: process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/scheduler',
options: {
ssl: process.env.NODE_ENV === 'production'
}
}
});
Common Issues
Connection Errors
If you encounter connection issues:
- Check MongoDB is running:
mongosh
(ormongo
for older versions) - Verify connection string: Ensure the database URL is correct
- Network access: Check firewall settings for MongoDB port (27017)
Permission Issues
For MongoDB Atlas or secured instances:
- Ensure your IP is whitelisted
- Verify username/password in connection string
- Check database access permissions