@bernierllc/job-scheduler 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,389 @@
1
+ # @bernierllc/job-scheduler
2
+
3
+ Cron-based job scheduling for recurring tasks with execution tracking and history.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @bernierllc/job-scheduler
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **Cron Expression Support** - Schedule recurring jobs using standard cron syntax
14
+ - **One-Time Scheduling** - Schedule jobs to run at specific dates/times
15
+ - **Job Management** - Pause, resume, and cancel jobs
16
+ - **Execution Tracking** - Complete history of job executions with success/failure status
17
+ - **Retry Logic** - Automatic retry with configurable delay for failed jobs
18
+ - **Statistics** - Job execution statistics including duration, success rate, and next run time
19
+ - **TypeScript Support** - Full type definitions included
20
+ - **Task Queue Integration** - Optional integration with @bernierllc/task-queue
21
+ - **Structured Error Handling** - Consistent error responses using PackageResult pattern
22
+
23
+ ## Usage
24
+
25
+ ### Basic Recurring Job
26
+
27
+ ```typescript
28
+ import { createJobScheduler } from '@bernierllc/job-scheduler';
29
+
30
+ const scheduler = createJobScheduler();
31
+
32
+ // Schedule a job to run every day at 9 AM
33
+ const result = scheduler.schedule('0 9 * * *', async () => {
34
+ console.log('Daily report generation');
35
+ // Your job logic here
36
+ }, {
37
+ name: 'daily-report',
38
+ metadata: { source: 'reports' }
39
+ });
40
+
41
+ if (result.success) {
42
+ console.log('Job scheduled:', result.data?.getId());
43
+ }
44
+ ```
45
+
46
+ ### One-Time Job
47
+
48
+ ```typescript
49
+ import { createJobScheduler } from '@bernierllc/job-scheduler';
50
+
51
+ const scheduler = createJobScheduler();
52
+
53
+ // Schedule a job to run at specific time
54
+ const publishDate = new Date('2025-10-15T10:00:00Z');
55
+ const result = scheduler.scheduleAt(publishDate, async () => {
56
+ console.log('Publishing blog post');
57
+ // Your job logic here
58
+ }, {
59
+ name: 'publish-post',
60
+ metadata: { postId: '12345' }
61
+ });
62
+
63
+ if (result.success) {
64
+ console.log('Job scheduled for:', publishDate.toISOString());
65
+ }
66
+ ```
67
+
68
+ ### Job with Retry Logic
69
+
70
+ ```typescript
71
+ const result = scheduler.schedule('0 * * * *', async () => {
72
+ // Job that might fail
73
+ await processData();
74
+ }, {
75
+ name: 'data-processor',
76
+ maxRetries: 3,
77
+ retryDelay: 5000 // 5 seconds
78
+ });
79
+ ```
80
+
81
+ ### Managing Jobs
82
+
83
+ ```typescript
84
+ // Pause a job
85
+ scheduler.pause(jobId);
86
+
87
+ // Resume a paused job
88
+ scheduler.resume(jobId);
89
+
90
+ // Cancel a job
91
+ scheduler.cancel(jobId);
92
+
93
+ // Cancel all jobs
94
+ scheduler.cancelAll();
95
+ ```
96
+
97
+ ### Retrieving Jobs
98
+
99
+ ```typescript
100
+ // Get specific job
101
+ const job = scheduler.getJob(jobId);
102
+ console.log('Job status:', job?.getStatus());
103
+
104
+ // Get all jobs
105
+ const allJobs = scheduler.getAllJobs();
106
+ console.log('Total jobs:', allJobs.length);
107
+
108
+ // Get jobs by status
109
+ import { JobStatus } from '@bernierllc/job-scheduler';
110
+ const activeJobs = scheduler.getJobsByStatus(JobStatus.SCHEDULED);
111
+ const pausedJobs = scheduler.getJobsByStatus(JobStatus.PAUSED);
112
+ ```
113
+
114
+ ### Job Statistics
115
+
116
+ ```typescript
117
+ // Get statistics for specific job
118
+ const stats = scheduler.getJobStatistics(jobId);
119
+ if (stats) {
120
+ console.log('Total executions:', stats.totalExecutions);
121
+ console.log('Successful:', stats.successfulExecutions);
122
+ console.log('Failed:', stats.failedExecutions);
123
+ console.log('Average duration:', stats.averageDuration, 'ms');
124
+ console.log('Last execution:', stats.lastExecution);
125
+ console.log('Next execution:', stats.nextExecution);
126
+ }
127
+
128
+ // Get overall scheduler statistics
129
+ const schedulerStats = scheduler.getSchedulerStatistics();
130
+ console.log('Total jobs:', schedulerStats.totalJobs);
131
+ console.log('Active jobs:', schedulerStats.activeJobs);
132
+ console.log('Paused jobs:', schedulerStats.pausedJobs);
133
+ ```
134
+
135
+ ### Execution History
136
+
137
+ ```typescript
138
+ const job = scheduler.getJob(jobId);
139
+ const executions = job?.getExecutions();
140
+
141
+ executions?.forEach(execution => {
142
+ console.log('Execution ID:', execution.executionId);
143
+ console.log('Start time:', execution.startTime);
144
+ console.log('Status:', execution.status);
145
+ console.log('Duration:', execution.duration, 'ms');
146
+ if (execution.error) {
147
+ console.log('Error:', execution.error);
148
+ }
149
+ });
150
+ ```
151
+
152
+ ### Validate Cron Expression
153
+
154
+ ```typescript
155
+ const validation = scheduler.validateCronExpression('0 9 * * *');
156
+ if (validation.success) {
157
+ console.log('Valid cron expression');
158
+ } else {
159
+ console.error('Invalid:', validation.error);
160
+ }
161
+ ```
162
+
163
+ ## Configuration
164
+
165
+ ```typescript
166
+ import { createJobScheduler } from '@bernierllc/job-scheduler';
167
+
168
+ const scheduler = createJobScheduler({
169
+ timezone: 'America/New_York',
170
+ maxConcurrentJobs: 10,
171
+ enableHistory: true,
172
+ historyRetention: 100,
173
+ enableTaskQueue: true,
174
+ taskQueueConfig: {
175
+ maxSize: 100,
176
+ priority: 1
177
+ }
178
+ });
179
+ ```
180
+
181
+ ### Configuration Options
182
+
183
+ | Option | Type | Default | Description |
184
+ |--------|------|---------|-------------|
185
+ | `timezone` | string | `'UTC'` | Timezone for cron scheduling |
186
+ | `maxConcurrentJobs` | number | `10` | Maximum concurrent jobs |
187
+ | `enableHistory` | boolean | `true` | Enable execution history tracking |
188
+ | `historyRetention` | number | `100` | Number of executions to retain |
189
+ | `enableTaskQueue` | boolean | `false` | Enable task queue integration |
190
+ | `taskQueueConfig` | object | - | Task queue configuration |
191
+
192
+ ## Cron Expression Format
193
+
194
+ The scheduler supports standard cron expressions:
195
+
196
+ ```
197
+ ┌───────────── second (optional, 0-59)
198
+ │ ┌───────────── minute (0-59)
199
+ │ │ ┌───────────── hour (0-23)
200
+ │ │ │ ┌───────────── day of month (1-31)
201
+ │ │ │ │ ┌───────────── month (1-12)
202
+ │ │ │ │ │ ┌───────────── day of week (0-7, 0 and 7 are Sunday)
203
+ │ │ │ │ │ │
204
+ │ │ │ │ │ │
205
+ * * * * * *
206
+ ```
207
+
208
+ ### Examples
209
+
210
+ - `0 9 * * *` - Every day at 9:00 AM
211
+ - `*/15 * * * *` - Every 15 minutes
212
+ - `0 */2 * * *` - Every 2 hours
213
+ - `0 9 * * 1` - Every Monday at 9:00 AM
214
+ - `0 0 1 * *` - First day of every month at midnight
215
+ - `* * * * * *` - Every second (with second precision)
216
+
217
+ ## API Reference
218
+
219
+ ### JobScheduler
220
+
221
+ Main scheduler class for managing jobs.
222
+
223
+ #### Methods
224
+
225
+ - `schedule(cronExpression, handler, options?)` - Schedule recurring job
226
+ - `scheduleAt(date, handler, options?)` - Schedule one-time job
227
+ - `cancel(jobId)` - Cancel a job
228
+ - `pause(jobId)` - Pause a job
229
+ - `resume(jobId)` - Resume a paused job
230
+ - `getJob(jobId)` - Get job by ID
231
+ - `getAllJobs()` - Get all jobs
232
+ - `getJobsByStatus(status)` - Filter jobs by status
233
+ - `getJobStatistics(jobId)` - Get job statistics
234
+ - `getSchedulerStatistics()` - Get overall statistics
235
+ - `validateCronExpression(expression)` - Validate cron expression
236
+ - `cancelAll()` - Cancel all jobs
237
+ - `shutdown()` - Shutdown scheduler
238
+
239
+ ### ScheduledJob
240
+
241
+ Represents a scheduled job instance.
242
+
243
+ #### Methods
244
+
245
+ - `getId()` - Get job ID
246
+ - `getName()` - Get job name
247
+ - `getType()` - Get job type (recurring/one-time)
248
+ - `getStatus()` - Get current status
249
+ - `getConfig()` - Get job configuration
250
+ - `getExecutions()` - Get execution history
251
+ - `getStatistics()` - Get job statistics
252
+ - `start()` - Start job execution
253
+ - `pause()` - Pause job
254
+ - `resume()` - Resume job
255
+ - `cancel()` - Cancel job
256
+
257
+ ### Types
258
+
259
+ ```typescript
260
+ enum JobStatus {
261
+ SCHEDULED = 'scheduled',
262
+ RUNNING = 'running',
263
+ PAUSED = 'paused',
264
+ COMPLETED = 'completed',
265
+ FAILED = 'failed',
266
+ CANCELLED = 'cancelled'
267
+ }
268
+
269
+ enum JobType {
270
+ RECURRING = 'recurring',
271
+ ONE_TIME = 'one-time'
272
+ }
273
+
274
+ interface JobExecution {
275
+ executionId: string;
276
+ jobId: string;
277
+ startTime: Date;
278
+ endTime?: Date;
279
+ status: JobStatus;
280
+ error?: string;
281
+ duration?: number;
282
+ }
283
+
284
+ interface JobStatistics {
285
+ totalExecutions: number;
286
+ successfulExecutions: number;
287
+ failedExecutions: number;
288
+ averageDuration: number;
289
+ lastExecution?: Date;
290
+ nextExecution?: Date;
291
+ }
292
+
293
+ interface JobSchedulerResult<T = unknown> {
294
+ success: boolean;
295
+ data?: T;
296
+ error?: string;
297
+ }
298
+ ```
299
+
300
+ ## Advanced Usage
301
+
302
+ ### Custom Job Names and Metadata
303
+
304
+ ```typescript
305
+ const result = scheduler.schedule('0 * * * *', handler, {
306
+ name: 'hourly-sync',
307
+ metadata: {
308
+ source: 'external-api',
309
+ priority: 'high',
310
+ owner: 'data-team'
311
+ }
312
+ });
313
+
314
+ // Access metadata later
315
+ const job = scheduler.getJob(result.data!.getId());
316
+ const config = job.getConfig();
317
+ console.log('Metadata:', config.metadata);
318
+ ```
319
+
320
+ ### Monitoring Job Execution
321
+
322
+ ```typescript
323
+ const job = scheduler.getJob(jobId);
324
+
325
+ // Check current status
326
+ console.log('Status:', job.getStatus());
327
+
328
+ // Get detailed statistics
329
+ const stats = job.getStatistics();
330
+ console.log('Success rate:',
331
+ (stats.successfulExecutions / stats.totalExecutions * 100).toFixed(2) + '%'
332
+ );
333
+
334
+ // Get execution history
335
+ const executions = job.getExecutions();
336
+ const recentFailures = executions
337
+ .filter(e => e.status === JobStatus.FAILED)
338
+ .slice(-5);
339
+
340
+ recentFailures.forEach(failure => {
341
+ console.log('Failed at:', failure.startTime);
342
+ console.log('Error:', failure.error);
343
+ });
344
+ ```
345
+
346
+ ### Graceful Shutdown
347
+
348
+ ```typescript
349
+ // Cleanup on application shutdown
350
+ process.on('SIGTERM', () => {
351
+ console.log('Shutting down scheduler...');
352
+ scheduler.shutdown();
353
+ process.exit(0);
354
+ });
355
+ ```
356
+
357
+ ## Integration Status
358
+
359
+ - **Logger**: ✅ Integrated - Uses @bernierllc/logger for comprehensive logging
360
+ - **Docs-Suite**: ✅ Ready - Complete TypeDoc documentation with examples
361
+ - **NeverHub**: ⚠️ Optional - Can publish job execution events when available
362
+
363
+ ## Error Handling
364
+
365
+ All operations return a `JobSchedulerResult` with structured error information:
366
+
367
+ ```typescript
368
+ const result = scheduler.schedule('invalid-cron', handler);
369
+ if (!result.success) {
370
+ console.error('Scheduling failed:', result.error);
371
+ // Handle error appropriately
372
+ }
373
+ ```
374
+
375
+ ## Dependencies
376
+
377
+ - `@bernierllc/logger` - Logging functionality
378
+ - `@bernierllc/task-queue` - Optional task queue integration
379
+ - `cron-parser` - Cron expression parsing
380
+
381
+ ## See Also
382
+
383
+ - [@bernierllc/cron-scheduler](../cron-scheduler) - Pure cron utilities
384
+ - [@bernierllc/task-queue](../task-queue) - Task queue management
385
+ - [@bernierllc/scheduler-service](../../service/scheduler-service) - High-level scheduling service
386
+
387
+ ## License
388
+
389
+ Copyright (c) 2025 Bernier LLC. All rights reserved.
@@ -0,0 +1,126 @@
1
+ import { ScheduledJob } from './ScheduledJob';
2
+ import { JobHandler, JobSchedulerConfig, JobSchedulerResult, JobStatus, JobStatistics } from './types';
3
+ /**
4
+ * Job scheduler for cron-based recurring tasks and one-time scheduled jobs
5
+ */
6
+ export declare class JobScheduler {
7
+ private readonly jobs;
8
+ private readonly logger;
9
+ private readonly config;
10
+ private nextJobId;
11
+ constructor(config?: JobSchedulerConfig);
12
+ /**
13
+ * Schedule a recurring job with cron expression
14
+ *
15
+ * @param cronExpression - Cron expression (e.g., '0 9 * * *' for daily at 9 AM)
16
+ * @param handler - Function to execute
17
+ * @param options - Additional job options
18
+ * @returns Scheduled job instance
19
+ */
20
+ schedule(cronExpression: string, handler: JobHandler, options?: {
21
+ name?: string;
22
+ metadata?: Record<string, unknown>;
23
+ maxRetries?: number;
24
+ retryDelay?: number;
25
+ }): JobSchedulerResult<ScheduledJob>;
26
+ /**
27
+ * Schedule a one-time job at specific date/time
28
+ *
29
+ * @param date - Date/time to execute the job
30
+ * @param handler - Function to execute
31
+ * @param options - Additional job options
32
+ * @returns Scheduled job instance
33
+ */
34
+ scheduleAt(date: Date, handler: JobHandler, options?: {
35
+ name?: string;
36
+ metadata?: Record<string, unknown>;
37
+ maxRetries?: number;
38
+ retryDelay?: number;
39
+ }): JobSchedulerResult<ScheduledJob>;
40
+ /**
41
+ * Cancel a scheduled job
42
+ *
43
+ * @param jobId - Job ID to cancel
44
+ * @returns Result indicating success or failure
45
+ */
46
+ cancel(jobId: string): JobSchedulerResult<void>;
47
+ /**
48
+ * Pause a scheduled job
49
+ *
50
+ * @param jobId - Job ID to pause
51
+ * @returns Result indicating success or failure
52
+ */
53
+ pause(jobId: string): JobSchedulerResult<void>;
54
+ /**
55
+ * Resume a paused job
56
+ *
57
+ * @param jobId - Job ID to resume
58
+ * @returns Result indicating success or failure
59
+ */
60
+ resume(jobId: string): JobSchedulerResult<void>;
61
+ /**
62
+ * Get a scheduled job by ID
63
+ *
64
+ * @param jobId - Job ID
65
+ * @returns Job instance or undefined
66
+ */
67
+ getJob(jobId: string): ScheduledJob | undefined;
68
+ /**
69
+ * Get all scheduled jobs
70
+ *
71
+ * @returns Array of all jobs
72
+ */
73
+ getAllJobs(): ScheduledJob[];
74
+ /**
75
+ * Get jobs by status
76
+ *
77
+ * @param status - Job status to filter by
78
+ * @returns Array of jobs with the specified status
79
+ */
80
+ getJobsByStatus(status: JobStatus): ScheduledJob[];
81
+ /**
82
+ * Get job statistics
83
+ *
84
+ * @param jobId - Job ID
85
+ * @returns Job statistics or undefined
86
+ */
87
+ getJobStatistics(jobId: string): JobStatistics | undefined;
88
+ /**
89
+ * Cancel all jobs
90
+ */
91
+ cancelAll(): void;
92
+ /**
93
+ * Get scheduler statistics
94
+ *
95
+ * @returns Overall scheduler statistics
96
+ */
97
+ getSchedulerStatistics(): {
98
+ totalJobs: number;
99
+ activeJobs: number;
100
+ pausedJobs: number;
101
+ completedJobs: number;
102
+ failedJobs: number;
103
+ };
104
+ /**
105
+ * Validate cron expression
106
+ *
107
+ * @param cronExpression - Cron expression to validate
108
+ * @returns Result indicating if expression is valid
109
+ */
110
+ validateCronExpression(cronExpression: string): JobSchedulerResult<void>;
111
+ /**
112
+ * Generate unique job ID
113
+ */
114
+ private generateJobId;
115
+ /**
116
+ * Shutdown scheduler and cancel all jobs
117
+ */
118
+ shutdown(): void;
119
+ }
120
+ /**
121
+ * Create a new job scheduler instance
122
+ *
123
+ * @param config - Scheduler configuration
124
+ * @returns JobScheduler instance
125
+ */
126
+ export declare function createJobScheduler(config?: JobSchedulerConfig): JobScheduler;
@@ -0,0 +1,295 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JobScheduler = void 0;
11
+ exports.createJobScheduler = createJobScheduler;
12
+ const cron_parser_1 = require("cron-parser");
13
+ const logger_1 = require("@bernierllc/logger");
14
+ const ScheduledJob_1 = require("./ScheduledJob");
15
+ const types_1 = require("./types");
16
+ /**
17
+ * Job scheduler for cron-based recurring tasks and one-time scheduled jobs
18
+ */
19
+ class JobScheduler {
20
+ constructor(config = {}) {
21
+ this.nextJobId = 1;
22
+ this.jobs = new Map();
23
+ this.logger = (0, logger_1.createLogger)();
24
+ this.config = {
25
+ timezone: 'UTC',
26
+ maxConcurrentJobs: 10,
27
+ enableHistory: true,
28
+ historyRetention: 100,
29
+ enableTaskQueue: false,
30
+ ...config
31
+ };
32
+ // Task queue integration is optional and not implemented in this version
33
+ if (this.config.enableTaskQueue) {
34
+ this.logger.info('Task queue integration requested but not implemented in this version');
35
+ }
36
+ this.logger.info('JobScheduler initialized');
37
+ }
38
+ /**
39
+ * Schedule a recurring job with cron expression
40
+ *
41
+ * @param cronExpression - Cron expression (e.g., '0 9 * * *' for daily at 9 AM)
42
+ * @param handler - Function to execute
43
+ * @param options - Additional job options
44
+ * @returns Scheduled job instance
45
+ */
46
+ schedule(cronExpression, handler, options = {}) {
47
+ try {
48
+ // Validate cron expression
49
+ (0, cron_parser_1.parseExpression)(cronExpression);
50
+ const jobId = this.generateJobId();
51
+ const jobConfig = {
52
+ id: jobId,
53
+ type: types_1.JobType.RECURRING,
54
+ handler,
55
+ cronExpression,
56
+ name: options.name,
57
+ metadata: options.metadata,
58
+ maxRetries: options.maxRetries,
59
+ retryDelay: options.retryDelay
60
+ };
61
+ const job = new ScheduledJob_1.ScheduledJob(jobConfig, this.logger);
62
+ this.jobs.set(jobId, job);
63
+ job.start();
64
+ this.logger.info('Recurring job scheduled', {
65
+ jobId,
66
+ name: options.name,
67
+ cronExpression
68
+ });
69
+ return {
70
+ success: true,
71
+ data: job
72
+ };
73
+ }
74
+ catch (error) {
75
+ const errorMessage = error instanceof Error ? error.message : String(error);
76
+ this.logger.error('Failed to schedule recurring job');
77
+ return {
78
+ success: false,
79
+ error: `Failed to schedule job: ${errorMessage}`
80
+ };
81
+ }
82
+ }
83
+ /**
84
+ * Schedule a one-time job at specific date/time
85
+ *
86
+ * @param date - Date/time to execute the job
87
+ * @param handler - Function to execute
88
+ * @param options - Additional job options
89
+ * @returns Scheduled job instance
90
+ */
91
+ scheduleAt(date, handler, options = {}) {
92
+ try {
93
+ const jobId = this.generateJobId();
94
+ const jobConfig = {
95
+ id: jobId,
96
+ type: types_1.JobType.ONE_TIME,
97
+ handler,
98
+ scheduledTime: date,
99
+ name: options.name,
100
+ metadata: options.metadata,
101
+ maxRetries: options.maxRetries,
102
+ retryDelay: options.retryDelay
103
+ };
104
+ const job = new ScheduledJob_1.ScheduledJob(jobConfig, this.logger);
105
+ this.jobs.set(jobId, job);
106
+ job.start();
107
+ this.logger.info('One-time job scheduled', {
108
+ jobId,
109
+ name: options.name,
110
+ scheduledTime: date.toISOString()
111
+ });
112
+ return {
113
+ success: true,
114
+ data: job
115
+ };
116
+ }
117
+ catch (error) {
118
+ const errorMessage = error instanceof Error ? error.message : String(error);
119
+ this.logger.error('Failed to schedule one-time job');
120
+ return {
121
+ success: false,
122
+ error: `Failed to schedule job: ${errorMessage}`
123
+ };
124
+ }
125
+ }
126
+ /**
127
+ * Cancel a scheduled job
128
+ *
129
+ * @param jobId - Job ID to cancel
130
+ * @returns Result indicating success or failure
131
+ */
132
+ cancel(jobId) {
133
+ const job = this.jobs.get(jobId);
134
+ if (!job) {
135
+ return {
136
+ success: false,
137
+ error: `Job not found: ${jobId}`
138
+ };
139
+ }
140
+ job.cancel();
141
+ this.jobs.delete(jobId);
142
+ this.logger.info('Job cancelled and removed', { jobId });
143
+ return { success: true };
144
+ }
145
+ /**
146
+ * Pause a scheduled job
147
+ *
148
+ * @param jobId - Job ID to pause
149
+ * @returns Result indicating success or failure
150
+ */
151
+ pause(jobId) {
152
+ const job = this.jobs.get(jobId);
153
+ if (!job) {
154
+ return {
155
+ success: false,
156
+ error: `Job not found: ${jobId}`
157
+ };
158
+ }
159
+ job.pause();
160
+ this.logger.info('Job paused', { jobId });
161
+ return { success: true };
162
+ }
163
+ /**
164
+ * Resume a paused job
165
+ *
166
+ * @param jobId - Job ID to resume
167
+ * @returns Result indicating success or failure
168
+ */
169
+ resume(jobId) {
170
+ const job = this.jobs.get(jobId);
171
+ if (!job) {
172
+ return {
173
+ success: false,
174
+ error: `Job not found: ${jobId}`
175
+ };
176
+ }
177
+ if (job.getStatus() !== types_1.JobStatus.PAUSED) {
178
+ return {
179
+ success: false,
180
+ error: `Job is not paused: ${jobId}`
181
+ };
182
+ }
183
+ job.resume();
184
+ this.logger.info('Job resumed', { jobId });
185
+ return { success: true };
186
+ }
187
+ /**
188
+ * Get a scheduled job by ID
189
+ *
190
+ * @param jobId - Job ID
191
+ * @returns Job instance or undefined
192
+ */
193
+ getJob(jobId) {
194
+ return this.jobs.get(jobId);
195
+ }
196
+ /**
197
+ * Get all scheduled jobs
198
+ *
199
+ * @returns Array of all jobs
200
+ */
201
+ getAllJobs() {
202
+ return Array.from(this.jobs.values());
203
+ }
204
+ /**
205
+ * Get jobs by status
206
+ *
207
+ * @param status - Job status to filter by
208
+ * @returns Array of jobs with the specified status
209
+ */
210
+ getJobsByStatus(status) {
211
+ return Array.from(this.jobs.values()).filter((job) => job.getStatus() === status);
212
+ }
213
+ /**
214
+ * Get job statistics
215
+ *
216
+ * @param jobId - Job ID
217
+ * @returns Job statistics or undefined
218
+ */
219
+ getJobStatistics(jobId) {
220
+ const job = this.jobs.get(jobId);
221
+ return job?.getStatistics();
222
+ }
223
+ /**
224
+ * Cancel all jobs
225
+ */
226
+ cancelAll() {
227
+ const jobIds = Array.from(this.jobs.keys());
228
+ for (const jobId of jobIds) {
229
+ this.cancel(jobId);
230
+ }
231
+ this.logger.info('All jobs cancelled', { count: jobIds.length });
232
+ }
233
+ /**
234
+ * Get scheduler statistics
235
+ *
236
+ * @returns Overall scheduler statistics
237
+ */
238
+ getSchedulerStatistics() {
239
+ const jobs = Array.from(this.jobs.values());
240
+ return {
241
+ totalJobs: jobs.length,
242
+ activeJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.SCHEDULED ||
243
+ j.getStatus() === types_1.JobStatus.RUNNING).length,
244
+ pausedJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.PAUSED).length,
245
+ completedJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.COMPLETED)
246
+ .length,
247
+ failedJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.FAILED).length
248
+ };
249
+ }
250
+ /**
251
+ * Validate cron expression
252
+ *
253
+ * @param cronExpression - Cron expression to validate
254
+ * @returns Result indicating if expression is valid
255
+ */
256
+ validateCronExpression(cronExpression) {
257
+ try {
258
+ (0, cron_parser_1.parseExpression)(cronExpression);
259
+ return { success: true };
260
+ }
261
+ catch (error) {
262
+ const errorMessage = error instanceof Error ? error.message : String(error);
263
+ return {
264
+ success: false,
265
+ error: `Invalid cron expression: ${errorMessage}`
266
+ };
267
+ }
268
+ }
269
+ /**
270
+ * Generate unique job ID
271
+ */
272
+ generateJobId() {
273
+ const id = `job-${this.nextJobId}`;
274
+ this.nextJobId++;
275
+ return id;
276
+ }
277
+ /**
278
+ * Shutdown scheduler and cancel all jobs
279
+ */
280
+ shutdown() {
281
+ this.logger.info('Shutting down scheduler');
282
+ this.cancelAll();
283
+ this.logger.info('Scheduler shutdown complete');
284
+ }
285
+ }
286
+ exports.JobScheduler = JobScheduler;
287
+ /**
288
+ * Create a new job scheduler instance
289
+ *
290
+ * @param config - Scheduler configuration
291
+ * @returns JobScheduler instance
292
+ */
293
+ function createJobScheduler(config) {
294
+ return new JobScheduler(config);
295
+ }
@@ -0,0 +1,70 @@
1
+ import { Logger } from '@bernierllc/logger';
2
+ import { JobStatus, JobType, ScheduledJobConfig, JobExecution, JobStatistics } from './types';
3
+ /**
4
+ * Represents a scheduled job with execution tracking
5
+ */
6
+ export declare class ScheduledJob {
7
+ private readonly config;
8
+ private status;
9
+ private readonly executions;
10
+ private timer?;
11
+ private readonly logger;
12
+ private currentRetries;
13
+ constructor(config: ScheduledJobConfig, logger: Logger);
14
+ /**
15
+ * Get job ID
16
+ */
17
+ getId(): string;
18
+ /**
19
+ * Get job name
20
+ */
21
+ getName(): string;
22
+ /**
23
+ * Get job type
24
+ */
25
+ getType(): JobType;
26
+ /**
27
+ * Get job status
28
+ */
29
+ getStatus(): JobStatus;
30
+ /**
31
+ * Get job configuration
32
+ */
33
+ getConfig(): Readonly<ScheduledJobConfig>;
34
+ /**
35
+ * Get job execution history
36
+ */
37
+ getExecutions(): readonly JobExecution[];
38
+ /**
39
+ * Get job statistics
40
+ */
41
+ getStatistics(): JobStatistics;
42
+ /**
43
+ * Start job execution
44
+ */
45
+ start(): void;
46
+ /**
47
+ * Pause job execution
48
+ */
49
+ pause(): void;
50
+ /**
51
+ * Resume job execution
52
+ */
53
+ resume(): void;
54
+ /**
55
+ * Cancel job execution
56
+ */
57
+ cancel(): void;
58
+ /**
59
+ * Execute job handler
60
+ */
61
+ private executeJob;
62
+ /**
63
+ * Schedule recurring job
64
+ */
65
+ private scheduleRecurring;
66
+ /**
67
+ * Schedule one-time job
68
+ */
69
+ private scheduleOneTime;
70
+ }
@@ -0,0 +1,279 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.ScheduledJob = void 0;
11
+ const cron_parser_1 = require("cron-parser");
12
+ const types_1 = require("./types");
13
+ /**
14
+ * Represents a scheduled job with execution tracking
15
+ */
16
+ class ScheduledJob {
17
+ constructor(config, logger) {
18
+ this.currentRetries = 0;
19
+ this.config = config;
20
+ this.status = types_1.JobStatus.SCHEDULED;
21
+ this.executions = [];
22
+ this.logger = logger;
23
+ }
24
+ /**
25
+ * Get job ID
26
+ */
27
+ getId() {
28
+ return this.config.id;
29
+ }
30
+ /**
31
+ * Get job name
32
+ */
33
+ getName() {
34
+ return this.config.name || this.config.id;
35
+ }
36
+ /**
37
+ * Get job type
38
+ */
39
+ getType() {
40
+ return this.config.type;
41
+ }
42
+ /**
43
+ * Get job status
44
+ */
45
+ getStatus() {
46
+ return this.status;
47
+ }
48
+ /**
49
+ * Get job configuration
50
+ */
51
+ getConfig() {
52
+ return Object.freeze({ ...this.config });
53
+ }
54
+ /**
55
+ * Get job execution history
56
+ */
57
+ getExecutions() {
58
+ return Object.freeze([...this.executions]);
59
+ }
60
+ /**
61
+ * Get job statistics
62
+ */
63
+ getStatistics() {
64
+ const successfulExecutions = this.executions.filter((e) => e.status === types_1.JobStatus.COMPLETED);
65
+ const failedExecutions = this.executions.filter((e) => e.status === types_1.JobStatus.FAILED);
66
+ const totalDuration = this.executions.reduce((sum, e) => sum + (e.duration || 0), 0);
67
+ const lastExecution = this.executions.length > 0
68
+ ? this.executions[this.executions.length - 1].startTime
69
+ : undefined;
70
+ let nextExecution;
71
+ if (this.config.type === types_1.JobType.RECURRING && this.config.cronExpression) {
72
+ try {
73
+ const interval = (0, cron_parser_1.parseExpression)(this.config.cronExpression);
74
+ nextExecution = interval.next().toDate();
75
+ }
76
+ catch (error) {
77
+ this.logger.error('Failed to calculate next execution');
78
+ }
79
+ }
80
+ else if (this.config.type === types_1.JobType.ONE_TIME && this.config.scheduledTime) {
81
+ nextExecution = this.config.scheduledTime;
82
+ }
83
+ return {
84
+ totalExecutions: this.executions.length,
85
+ successfulExecutions: successfulExecutions.length,
86
+ failedExecutions: failedExecutions.length,
87
+ averageDuration: this.executions.length > 0 ? totalDuration / this.executions.length : 0,
88
+ lastExecution,
89
+ nextExecution
90
+ };
91
+ }
92
+ /**
93
+ * Start job execution
94
+ */
95
+ start() {
96
+ if (this.status === types_1.JobStatus.RUNNING) {
97
+ this.logger.warn('Job is already running', { jobId: this.config.id });
98
+ return;
99
+ }
100
+ if (this.status === types_1.JobStatus.CANCELLED) {
101
+ this.logger.warn('Cannot start cancelled job', { jobId: this.config.id });
102
+ return;
103
+ }
104
+ this.status = types_1.JobStatus.SCHEDULED;
105
+ if (this.config.type === types_1.JobType.RECURRING) {
106
+ if (!this.config.cronExpression) {
107
+ throw new Error('Cron expression is required for recurring jobs');
108
+ }
109
+ this.scheduleRecurring();
110
+ }
111
+ else if (this.config.type === types_1.JobType.ONE_TIME) {
112
+ if (!this.config.scheduledTime) {
113
+ throw new Error('Scheduled time is required for one-time jobs');
114
+ }
115
+ this.scheduleOneTime();
116
+ }
117
+ this.logger.info('Job started', {
118
+ jobId: this.config.id,
119
+ type: this.config.type,
120
+ name: this.config.name
121
+ });
122
+ }
123
+ /**
124
+ * Pause job execution
125
+ */
126
+ pause() {
127
+ if (this.status === types_1.JobStatus.RUNNING) {
128
+ this.logger.warn('Cannot pause running job', { jobId: this.config.id });
129
+ return;
130
+ }
131
+ if (this.timer) {
132
+ clearTimeout(this.timer);
133
+ this.timer = undefined;
134
+ }
135
+ this.status = types_1.JobStatus.PAUSED;
136
+ this.logger.info('Job paused', { jobId: this.config.id });
137
+ }
138
+ /**
139
+ * Resume job execution
140
+ */
141
+ resume() {
142
+ if (this.status !== types_1.JobStatus.PAUSED) {
143
+ this.logger.warn('Job is not paused', { jobId: this.config.id });
144
+ return;
145
+ }
146
+ this.start();
147
+ this.logger.info('Job resumed', { jobId: this.config.id });
148
+ }
149
+ /**
150
+ * Cancel job execution
151
+ */
152
+ cancel() {
153
+ if (this.timer) {
154
+ clearTimeout(this.timer);
155
+ this.timer = undefined;
156
+ }
157
+ this.status = types_1.JobStatus.CANCELLED;
158
+ this.logger.info('Job cancelled', { jobId: this.config.id });
159
+ }
160
+ /**
161
+ * Execute job handler
162
+ */
163
+ async executeJob() {
164
+ const executionId = `${this.config.id}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
165
+ const startTime = new Date();
166
+ const execution = {
167
+ executionId,
168
+ jobId: this.config.id,
169
+ startTime,
170
+ status: types_1.JobStatus.RUNNING
171
+ };
172
+ this.executions.push(execution);
173
+ this.status = types_1.JobStatus.RUNNING;
174
+ this.logger.info('Job execution started', {
175
+ executionId,
176
+ jobId: this.config.id,
177
+ name: this.config.name
178
+ });
179
+ try {
180
+ await this.config.handler();
181
+ const endTime = new Date();
182
+ execution.endTime = endTime;
183
+ execution.status = types_1.JobStatus.COMPLETED;
184
+ execution.duration = endTime.getTime() - startTime.getTime();
185
+ this.currentRetries = 0;
186
+ this.logger.info('Job execution completed', {
187
+ executionId,
188
+ jobId: this.config.id,
189
+ duration: execution.duration
190
+ });
191
+ }
192
+ catch (error) {
193
+ const endTime = new Date();
194
+ execution.endTime = endTime;
195
+ execution.status = types_1.JobStatus.FAILED;
196
+ execution.duration = endTime.getTime() - startTime.getTime();
197
+ execution.error = error instanceof Error ? error.message : String(error);
198
+ this.logger.error('Job execution failed');
199
+ // Handle retries
200
+ if (this.config.maxRetries &&
201
+ this.currentRetries < this.config.maxRetries) {
202
+ this.currentRetries++;
203
+ const retryDelay = this.config.retryDelay || 5000;
204
+ this.logger.info('Scheduling job retry', {
205
+ jobId: this.config.id,
206
+ retry: this.currentRetries,
207
+ maxRetries: this.config.maxRetries,
208
+ delay: retryDelay
209
+ });
210
+ setTimeout(() => {
211
+ void this.executeJob();
212
+ }, retryDelay);
213
+ }
214
+ }
215
+ finally {
216
+ this.status = types_1.JobStatus.SCHEDULED;
217
+ // Schedule next execution for recurring jobs
218
+ if (this.config.type === types_1.JobType.RECURRING &&
219
+ this.status === types_1.JobStatus.SCHEDULED) {
220
+ this.scheduleRecurring();
221
+ }
222
+ else if (this.config.type === types_1.JobType.ONE_TIME) {
223
+ this.status = types_1.JobStatus.COMPLETED;
224
+ this.logger.info('One-time job completed');
225
+ }
226
+ }
227
+ }
228
+ /**
229
+ * Schedule recurring job
230
+ */
231
+ scheduleRecurring() {
232
+ if (!this.config.cronExpression) {
233
+ throw new Error('Cron expression is required for recurring jobs');
234
+ }
235
+ try {
236
+ const interval = (0, cron_parser_1.parseExpression)(this.config.cronExpression);
237
+ const nextRun = interval.next().toDate();
238
+ const delay = nextRun.getTime() - Date.now();
239
+ this.timer = setTimeout(() => {
240
+ void this.executeJob();
241
+ }, delay);
242
+ this.logger.debug('Recurring job scheduled', {
243
+ jobId: this.config.id,
244
+ nextRun: nextRun.toISOString(),
245
+ delay
246
+ });
247
+ }
248
+ catch (error) {
249
+ this.logger.error('Failed to schedule recurring job');
250
+ throw error;
251
+ }
252
+ }
253
+ /**
254
+ * Schedule one-time job
255
+ */
256
+ scheduleOneTime() {
257
+ if (!this.config.scheduledTime) {
258
+ throw new Error('Scheduled time is required for one-time jobs');
259
+ }
260
+ const delay = this.config.scheduledTime.getTime() - Date.now();
261
+ if (delay < 0) {
262
+ this.logger.warn('Scheduled time is in the past, executing immediately', {
263
+ jobId: this.config.id,
264
+ scheduledTime: this.config.scheduledTime.toISOString()
265
+ });
266
+ void this.executeJob();
267
+ return;
268
+ }
269
+ this.timer = setTimeout(() => {
270
+ void this.executeJob();
271
+ }, delay);
272
+ this.logger.debug('One-time job scheduled', {
273
+ jobId: this.config.id,
274
+ scheduledTime: this.config.scheduledTime.toISOString(),
275
+ delay
276
+ });
277
+ }
278
+ }
279
+ exports.ScheduledJob = ScheduledJob;
@@ -0,0 +1,3 @@
1
+ export { JobScheduler, createJobScheduler } from './JobScheduler';
2
+ export { ScheduledJob } from './ScheduledJob';
3
+ export { JobStatus, JobType, JobHandler, JobExecution, ScheduledJobConfig, JobSchedulerConfig, JobSchedulerResult, JobStatistics } from './types';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JobType = exports.JobStatus = exports.ScheduledJob = exports.createJobScheduler = exports.JobScheduler = void 0;
11
+ var JobScheduler_1 = require("./JobScheduler");
12
+ Object.defineProperty(exports, "JobScheduler", { enumerable: true, get: function () { return JobScheduler_1.JobScheduler; } });
13
+ Object.defineProperty(exports, "createJobScheduler", { enumerable: true, get: function () { return JobScheduler_1.createJobScheduler; } });
14
+ var ScheduledJob_1 = require("./ScheduledJob");
15
+ Object.defineProperty(exports, "ScheduledJob", { enumerable: true, get: function () { return ScheduledJob_1.ScheduledJob; } });
16
+ var types_1 = require("./types");
17
+ Object.defineProperty(exports, "JobStatus", { enumerable: true, get: function () { return types_1.JobStatus; } });
18
+ Object.defineProperty(exports, "JobType", { enumerable: true, get: function () { return types_1.JobType; } });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Job execution status
3
+ */
4
+ export declare enum JobStatus {
5
+ SCHEDULED = "scheduled",
6
+ RUNNING = "running",
7
+ PAUSED = "paused",
8
+ COMPLETED = "completed",
9
+ FAILED = "failed",
10
+ CANCELLED = "cancelled"
11
+ }
12
+ /**
13
+ * Job type
14
+ */
15
+ export declare enum JobType {
16
+ RECURRING = "recurring",
17
+ ONE_TIME = "one-time"
18
+ }
19
+ /**
20
+ * Job handler function
21
+ */
22
+ export type JobHandler = () => void | Promise<void>;
23
+ /**
24
+ * Job execution record
25
+ */
26
+ export interface JobExecution {
27
+ executionId: string;
28
+ jobId: string;
29
+ startTime: Date;
30
+ endTime?: Date;
31
+ status: JobStatus;
32
+ error?: string;
33
+ duration?: number;
34
+ }
35
+ /**
36
+ * Scheduled job configuration
37
+ */
38
+ export interface ScheduledJobConfig {
39
+ id: string;
40
+ type: JobType;
41
+ handler: JobHandler;
42
+ cronExpression?: string;
43
+ scheduledTime?: Date;
44
+ name?: string;
45
+ metadata?: Record<string, unknown>;
46
+ maxRetries?: number;
47
+ retryDelay?: number;
48
+ }
49
+ /**
50
+ * Job scheduler configuration
51
+ */
52
+ export interface JobSchedulerConfig {
53
+ timezone?: string;
54
+ maxConcurrentJobs?: number;
55
+ enableHistory?: boolean;
56
+ historyRetention?: number;
57
+ enableTaskQueue?: boolean;
58
+ taskQueueConfig?: {
59
+ maxSize?: number;
60
+ priority?: number;
61
+ };
62
+ }
63
+ /**
64
+ * Job scheduler result
65
+ */
66
+ export interface JobSchedulerResult<T = unknown> {
67
+ success: boolean;
68
+ data?: T;
69
+ error?: string;
70
+ }
71
+ /**
72
+ * Job statistics
73
+ */
74
+ export interface JobStatistics {
75
+ totalExecutions: number;
76
+ successfulExecutions: number;
77
+ failedExecutions: number;
78
+ averageDuration: number;
79
+ lastExecution?: Date;
80
+ nextExecution?: Date;
81
+ }
package/dist/types.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /*
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ This file is licensed to the client under a limited-use license.
6
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
7
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JobType = exports.JobStatus = void 0;
11
+ /**
12
+ * Job execution status
13
+ */
14
+ var JobStatus;
15
+ (function (JobStatus) {
16
+ JobStatus["SCHEDULED"] = "scheduled";
17
+ JobStatus["RUNNING"] = "running";
18
+ JobStatus["PAUSED"] = "paused";
19
+ JobStatus["COMPLETED"] = "completed";
20
+ JobStatus["FAILED"] = "failed";
21
+ JobStatus["CANCELLED"] = "cancelled";
22
+ })(JobStatus || (exports.JobStatus = JobStatus = {}));
23
+ /**
24
+ * Job type
25
+ */
26
+ var JobType;
27
+ (function (JobType) {
28
+ JobType["RECURRING"] = "recurring";
29
+ JobType["ONE_TIME"] = "one-time";
30
+ })(JobType || (exports.JobType = JobType = {}));
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@bernierllc/job-scheduler",
3
+ "version": "1.0.0",
4
+ "description": "Cron-based job scheduling for recurring tasks with execution tracking",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "prebuild": "npm run clean",
10
+ "clean": "rimraf dist",
11
+ "test": "jest --watch",
12
+ "test:watch": "jest --watch",
13
+ "test:coverage": "jest --coverage",
14
+ "test:run": "jest",
15
+ "lint": "eslint src __tests__ --ext .ts"
16
+ },
17
+ "files": [
18
+ "dist/**/*",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "keywords": [
23
+ "cron",
24
+ "scheduler",
25
+ "jobs",
26
+ "recurring",
27
+ "task",
28
+ "automation",
29
+ "core"
30
+ ],
31
+ "author": "Bernier LLC",
32
+ "license": "SEE LICENSE IN LICENSE",
33
+ "dependencies": {
34
+ "@bernierllc/logger": "^1.0.1",
35
+ "cron-parser": "^4.9.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^20.0.0",
39
+ "@types/jest": "^29.0.0",
40
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
41
+ "@typescript-eslint/parser": "^6.0.0",
42
+ "eslint": "^8.0.0",
43
+ "jest": "^29.0.0",
44
+ "rimraf": "^5.0.0",
45
+ "ts-jest": "^29.0.0",
46
+ "typescript": "^5.0.0"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/bernierllc/tools.git",
51
+ "directory": "packages/core/job-scheduler"
52
+ },
53
+ "bugs": {
54
+ "url": "https://github.com/bernierllc/tools/issues"
55
+ },
56
+ "homepage": "https://github.com/bernierllc/tools/tree/main/packages/core/job-scheduler#readme",
57
+ "publishConfig": {
58
+ "access": "restricted"
59
+ },
60
+ "engines": {
61
+ "node": ">=16.0.0"
62
+ },
63
+ "bernierllc": {
64
+ "integration": {
65
+ "neverhub": "optional"
66
+ }
67
+ }
68
+ }