cronflex
v1.4.0
Published
A robust JavaScript task queue, cron scheduler, and rate-limiting library
Maintainers
Readme
⚡ CronFlex
A robust, enterprise-grade, zero-dependency task queue, cron scheduler, and rate-limiting library for Node.js and browser environments. It comes out-of-the-box with a premium, glassmorphic monitoring web dashboard to manage all your tasks and schedules in real-time.
Created by: moaaz yahia zakaria (من صنع معاذ يحيى زكريا)
🚀 Why CronFlex?
Unlike other heavy solutions that require configuring external services like Redis or database backends just to run simple background tasks, CronFlex gives you complete control over your application's concurrency, rate-limits, and cron schedules locally, with zero setup.
Feature Comparison
| Feature | CronFlex | BullMQ | node-cron | p-queue | | :--- | :---: | :---: | :---: | :---: | | Dependencies | 0 (Zero) | Heavy | Medium | 0 (Zero) | | Requires Redis/DB | No (Optional) | Yes | No | No | | Task Queue | ✅ | ✅ | ❌ | ✅ | | Cron Scheduler | ✅ | ❌ | ✅ | ❌ | | Token Rate Limiting| ✅ | ✅ | ❌ | ❌ | | Native Web UI | ✅ (Included) | ❌ (BullBoard) | ❌ | ❌ | | Dependency Chains | ✅ | ✅ | ❌ | ❌ |
✨ Features
- ⚡ Lightweight & Zero-Dependency: Extremely fast, small bundle footprint, and runs anywhere.
- ⏰ Full Cron Scheduler: Run recurring tasks using standard 5-field cron expressions.
- ⚡ Advanced Task Queue: Priorities, dependency chains, delayed runs, TTL, timeouts, and retries.
- ⏱️ Token Rate Limiter & Concurrency: Restrict concurrent runs and throttle excessive operations.
- 💾 State Persistence: Save & restore queue state seamlessly (via Redis, LocalStorage, or custom adapters).
- 🖥️ Premium Monitoring Dashboard: Native, lightweight HTTP server providing a stunning glassmorphic UI to manage everything at runtime.
📦 Installation
npm install cronflex🏁 Quick Start
Here is a quick example showing how to initialize TaskPulse (the core class of CronFlex) and register tasks.
import { TaskPulse } from 'cronflex';
// 1. Initialize with custom concurrency and background server
const tp = new TaskPulse({
concurrency: 3, // Max 3 parallel running tasks
rateMax: 10, // Max 10 runs per window
rateWindow: 5000, // Window duration: 5 seconds
server: {
enabled: true, // Start the web dashboard server
port: 3000,
host: '0.0.0.0'
}
});
// 2. Add a simple task
tp.add({ id: 'welcome-email' }, async () => {
console.log('Sending welcome email...');
return { sent: true };
});
// 3. Register a recurring Cron Job
tp.cron('cleanup-logs', { cronExpression: '0 * * * *' }, async () => {
console.log('Cleaning logs database...');
});Now, open your browser and navigate to http://localhost:3000 to monitor and control these tasks live!
🛠️ Advanced Usage
1. Delayed Tasks
Delayed tasks are immediately enqueued in the queue with a delayed status. They show up in your dashboard with a live countdown timer and execute automatically once the delay finishes.
tp.add(
{
id: 'db-sync',
delay: 5000, // Executes after 5 seconds
},
async () => {
console.log('Synchronizing database...');
}
);2. Periodic Tasks
Periodic tasks run repeatedly at a specific interval. Between runs, they enter a Waiting status showing a live countdown until the next run.
tp.add(
{
id: 'health-check',
isPeriodic: true,
periodInterval: 10000, // Run every 10 seconds
},
async () => {
console.log('Pinging health check endpoint...');
}
);3. Task Dependencies
Ensure task execution order. compile-project will only run once both fetch-code and install-deps have completed successfully.
tp.add({ id: 'fetch-code' }, async () => { /* ... */ });
tp.add({ id: 'install-deps' }, async () => { /* ... */ });
tp.add(
{
id: 'compile-project',
dependencies: ['fetch-code', 'install-deps']
},
async () => {
console.log('Compiling project files...');
}
);🖥️ Interactive Web Dashboard
The built-in web dashboard provides a gorgeous, glassmorphic UI loaded with real-time controls:
- Queue Status & Concurrency: Toggle active status (Pause/Resume Queue) and update concurrency limits or rate limits live.
- Active & Queued Tasks: Check active tasks, their status (
Running,Queued,Delayedwith live countdowns,Waitingwith live countdowns), and change task priority on the fly. - Cron Scheduler Management: Add new cron jobs dynamically by selecting from templates, pause/resume active crons, delete crons, or trigger them instantly.
- Dead Letter Queue: Keep track of failed tasks, dismiss them, or trigger manual retries.
- Execution Logs & Metrics: Interactive performance statistics (success rate, average latency, and runtime duration).
- Real-Time Live Updates: The dashboard receives instant status pushes over Server-Sent Events (
/api/events), automatically falling back to 1-second polling on older browsers or when SSE is unavailable.
📖 API Reference
TaskPulseOptions
concurrency?: number(Default:3): Maximum parallel running tasks.rateMax?: number: Maximum tokens/runs in the rate-limiting window.rateWindow?: number: Duration of the rate window in ms.persist?: boolean(Default:false): Enables state persistence.saveState?: (state: any[]) => void: Handler to serialize state.loadState?: () => any[]: Handler to reload state.server?: { enabled?: boolean; port?: number; host?: string; path?: string; }: Configurations for the native dashboard server.
Core Methods
add(options: TaskOptions, execute: TaskExecuteFn): void: Enqueue a task.addBatch(tasks: Array<{ options, execute }>): void: Enqueue multiple tasks.cron(id: string, options: CronTaskOptions, execute: TaskExecuteFn): CronJob: Register a recurring cron task.uncron(id: string): boolean: Delete and unschedule a cron job.pause() / resume(): Control queue execution.setConcurrency(n: number) / setRateLimit(max: number, window?: number): Adjust limits dynamically.clearQueue() / clearFailed(): Clean active queues and dead-letter logs.
🤝 Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
Distributed under the MIT License. See LICENSE for more information.
