Quick Start Guide
Get up and running with Chronos in less than 5 minutes! This guide will walk you through creating your first scheduled job.
Step 1: Initialize Chronos
First, create and configure your Chronos instance:
const { Chronos } = require('chronos-jobs');
const mongoConnectionString = 'mongodb://127.0.0.1/scheduler';
const scheduler = new Chronos({
db: { address: mongoConnectionString }
});
Step 2: Define Your First Job
Define what happens when a job runs:
scheduler.define('send notification', async (job) => {
const { userId, message } = job.attrs.data;
console.log(`Sending notification to user ${userId}: ${message}`);
// Your job logic here
// await sendEmail(userId, message);
// await sendPushNotification(userId, message);
});
Step 3: Start the Scheduler
Before scheduling any jobs, start the scheduler:
(async function() {
await scheduler.start();
console.log('Chronos scheduler started!');
})();
Step 4: Schedule Jobs
Now you can schedule jobs in different ways:
Immediate Execution
await scheduler.now('send notification', {
userId: 'user123',
message: 'Welcome to our app!'
});
Delayed Execution
await scheduler.schedule('in 5 minutes', 'send notification', {
userId: 'user123',
message: 'Don\'t forget to complete your profile!'
});
Recurring Jobs
await scheduler.every('30 minutes', 'send notification', {
userId: 'user123',
message: 'Regular check-in reminder'
});
Complete Example
Here's a complete working example:
const { Chronos } = require('chronos-jobs');
// Initialize Chronos
const scheduler = new Chronos({
db: { address: 'mongodb://127.0.0.1:27017/quickstart' }
});
// Define jobs
scheduler.define('cleanup old data', async (job) => {
console.log('Cleaning up old data...');
// Your cleanup logic here
console.log('Cleanup completed!');
});
scheduler.define('send daily report', async (job) => {
const { reportType } = job.attrs.data;
console.log(`Generating ${reportType} report...`);
// Your report generation logic here
console.log('Report sent!');
});
scheduler.define('user onboarding', async (job) => {
const { userId, step } = job.attrs.data;
console.log(`Processing onboarding step ${step} for user ${userId}`);
// Your onboarding logic here
});
// Main function
(async function main() {
try {
// Start the scheduler
await scheduler.start();
console.log('✅ Chronos started successfully!');
// Schedule immediate job
await scheduler.now('cleanup old data');
// Schedule delayed job
await scheduler.schedule('tomorrow at 9am', 'send daily report', {
reportType: 'analytics'
});
// Schedule recurring job
await scheduler.every('24 hours', 'send daily report', {
reportType: 'daily summary'
});
// Schedule user onboarding sequence
await scheduler.schedule('in 1 hour', 'user onboarding', {
userId: 'new_user_123',
step: 1
});
console.log('✅ All jobs scheduled successfully!');
} catch (error) {
console.error('❌ Error:', error);
}
})();
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log('Shutting down gracefully...');
await scheduler.stop();
process.exit(0);
});
Common Patterns
Error Handling
scheduler.define('risky job', async (job) => {
try {
// Your job logic
await riskyOperation();
} catch (error) {
console.error('Job failed:', error);
// Optionally fail the job
job.fail(error);
throw error; // Re-throw to mark job as failed
}
});
Job Data Validation
scheduler.define('process user data', async (job) => {
const { userId, action } = job.attrs.data;
if (!userId || !action) {
throw new Error('Missing required job data');
}
// Process the job
});
Conditional Scheduling
// Only schedule if not already exists
const existingJobs = await scheduler.jobs({ name: 'daily cleanup' });
if (existingJobs.length === 0) {
await scheduler.every('1 day', 'daily cleanup');
}
Ready to dive deeper? Continue with Basic Concepts to understand Chronos fundamentals.