@toolkit-p2p/cron
v0.1.0
Published
Distributed cron job scheduler for P2P applications
Maintainers
Readme
@toolkit-p2p/cron
Distributed cron job scheduler for P2P applications with standard 5-field cron expression support.
Features
- Standard 5-field cron expression parsing (minute hour day month weekday)
- Job scheduling with automatic execution
- Job lifecycle management (enable, disable, query)
- Retry and timeout support
- Execution history tracking
- Optional persistence via storage adapter
- Statistics and monitoring
Installation
npm install @toolkit-p2p/cronUsage
import { CronScheduler } from '@toolkit-p2p/cron';
// Create scheduler
const scheduler = new CronScheduler();
// Add a job
await scheduler.addJob({
name: 'daily-cleanup',
schedule: '0 0 * * *', // Daily at midnight
handler: async (context) => {
console.log(`Running ${context.jobName} at ${new Date(context.executionTime)}`);
// Your job logic here
},
metadata: { priority: 'high' },
});
// Query jobs
const jobs = scheduler.queryJobs({ enabled: true });
// Get statistics
const stats = scheduler.getStats();
console.log(`Total jobs: ${stats.totalJobs}, Enabled: ${stats.enabledJobs}`);Cron Expression Format
The scheduler supports standard 5-field cron expressions:
* * * * *
│ │ │ │ │
│ │ │ │ └─ Day of week (0-6, 0=Sunday)
│ │ │ └─── Month (1-12)
│ │ └───── Day of month (1-31)
│ └─────── Hour (0-23)
└───────── Minute (0-59)Examples
* * * * *- Every minute0 * * * *- Every hour0 0 * * *- Daily at midnight0 0 * * 0- Every Sunday at midnight*/5 * * * *- Every 5 minutes0,30 * * * *- Every hour at 0 and 30 minutes0-15 * * * *- First 15 minutes of every hour
API
CronScheduler
Constructor
const scheduler = new CronScheduler(options?: SchedulerOptions);Options:
autoStart- Auto-start scheduler (default: true)checkIntervalMs- Job check interval (default: 1000ms)maxConcurrentJobs- Max concurrent jobs (default: 10)enablePersistence- Enable persistence (default: false)storageAdapter- Storage adapter for persistencedefaultTimezone- Default timezone (default: 'UTC')
Methods
addJob(options)- Add a new jobremoveJob(jobId)- Remove a jobgetJob(jobId)- Get job by IDenableJob(jobId)- Enable a jobdisableJob(jobId)- Disable a jobqueryJobs(query?)- Query jobs with filtersgetStats()- Get scheduler statisticsstart()- Start the schedulerstop()- Stop the scheduler
Job Options
interface CreateJobOptions {
name: string;
schedule: string;
handler: (context: JobContext) => void | Promise<void>;
metadata?: Record<string, unknown>;
enabled?: boolean;
maxRetries?: number;
retryDelayMs?: number;
timeoutMs?: number;
timezone?: string;
}Job Context
Job handlers receive a context object:
interface JobContext {
jobId: string;
jobName: string;
scheduledTime: number;
executionTime: number;
runCount: number;
metadata?: Record<string, unknown>;
signal?: AbortSignal;
}Testing
pnpm testLicense
MIT
