@bernierllc/job-scheduler 1.5.0 → 1.5.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bernierllc/job-scheduler",
3
- "version": "1.5.0",
3
+ "version": "1.5.2",
4
4
  "description": "Cron-based job scheduling for recurring tasks with execution tracking",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -22,7 +22,7 @@
22
22
  "license": "SEE LICENSE IN LICENSE",
23
23
  "dependencies": {
24
24
  "cron-parser": "^4.9.0",
25
- "@bernierllc/logger": "1.7.0"
25
+ "@bernierllc/logger": "2.0.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/jest": "^29.0.0",
@@ -1,126 +0,0 @@
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;
@@ -1,298 +0,0 @@
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
- jobs;
21
- logger;
22
- config;
23
- nextJobId = 1;
24
- constructor(config = {}) {
25
- this.jobs = new Map();
26
- this.logger = (0, logger_1.createLogger)();
27
- this.config = {
28
- timezone: 'UTC',
29
- maxConcurrentJobs: 10,
30
- enableHistory: true,
31
- historyRetention: 100,
32
- enableTaskQueue: false,
33
- ...config
34
- };
35
- // Task queue integration is optional and not implemented in this version
36
- if (this.config.enableTaskQueue) {
37
- this.logger.info('Task queue integration requested but not implemented in this version');
38
- }
39
- this.logger.info('JobScheduler initialized');
40
- }
41
- /**
42
- * Schedule a recurring job with cron expression
43
- *
44
- * @param cronExpression - Cron expression (e.g., '0 9 * * *' for daily at 9 AM)
45
- * @param handler - Function to execute
46
- * @param options - Additional job options
47
- * @returns Scheduled job instance
48
- */
49
- schedule(cronExpression, handler, options = {}) {
50
- try {
51
- // Validate cron expression
52
- (0, cron_parser_1.parseExpression)(cronExpression);
53
- const jobId = this.generateJobId();
54
- const jobConfig = {
55
- id: jobId,
56
- type: types_1.JobType.RECURRING,
57
- handler,
58
- cronExpression,
59
- name: options.name,
60
- metadata: options.metadata,
61
- maxRetries: options.maxRetries,
62
- retryDelay: options.retryDelay
63
- };
64
- const job = new ScheduledJob_1.ScheduledJob(jobConfig, this.logger);
65
- this.jobs.set(jobId, job);
66
- job.start();
67
- this.logger.info('Recurring job scheduled', {
68
- jobId,
69
- name: options.name,
70
- cronExpression
71
- });
72
- return {
73
- success: true,
74
- data: job
75
- };
76
- }
77
- catch (error) {
78
- const errorMessage = error instanceof Error ? error.message : String(error);
79
- this.logger.error('Failed to schedule recurring job');
80
- return {
81
- success: false,
82
- error: `Failed to schedule job: ${errorMessage}`
83
- };
84
- }
85
- }
86
- /**
87
- * Schedule a one-time job at specific date/time
88
- *
89
- * @param date - Date/time to execute the job
90
- * @param handler - Function to execute
91
- * @param options - Additional job options
92
- * @returns Scheduled job instance
93
- */
94
- scheduleAt(date, handler, options = {}) {
95
- try {
96
- const jobId = this.generateJobId();
97
- const jobConfig = {
98
- id: jobId,
99
- type: types_1.JobType.ONE_TIME,
100
- handler,
101
- scheduledTime: date,
102
- name: options.name,
103
- metadata: options.metadata,
104
- maxRetries: options.maxRetries,
105
- retryDelay: options.retryDelay
106
- };
107
- const job = new ScheduledJob_1.ScheduledJob(jobConfig, this.logger);
108
- this.jobs.set(jobId, job);
109
- job.start();
110
- this.logger.info('One-time job scheduled', {
111
- jobId,
112
- name: options.name,
113
- scheduledTime: date.toISOString()
114
- });
115
- return {
116
- success: true,
117
- data: job
118
- };
119
- }
120
- catch (error) {
121
- const errorMessage = error instanceof Error ? error.message : String(error);
122
- this.logger.error('Failed to schedule one-time job');
123
- return {
124
- success: false,
125
- error: `Failed to schedule job: ${errorMessage}`
126
- };
127
- }
128
- }
129
- /**
130
- * Cancel a scheduled job
131
- *
132
- * @param jobId - Job ID to cancel
133
- * @returns Result indicating success or failure
134
- */
135
- cancel(jobId) {
136
- const job = this.jobs.get(jobId);
137
- if (!job) {
138
- return {
139
- success: false,
140
- error: `Job not found: ${jobId}`
141
- };
142
- }
143
- job.cancel();
144
- this.jobs.delete(jobId);
145
- this.logger.info('Job cancelled and removed', { jobId });
146
- return { success: true };
147
- }
148
- /**
149
- * Pause a scheduled job
150
- *
151
- * @param jobId - Job ID to pause
152
- * @returns Result indicating success or failure
153
- */
154
- pause(jobId) {
155
- const job = this.jobs.get(jobId);
156
- if (!job) {
157
- return {
158
- success: false,
159
- error: `Job not found: ${jobId}`
160
- };
161
- }
162
- job.pause();
163
- this.logger.info('Job paused', { jobId });
164
- return { success: true };
165
- }
166
- /**
167
- * Resume a paused job
168
- *
169
- * @param jobId - Job ID to resume
170
- * @returns Result indicating success or failure
171
- */
172
- resume(jobId) {
173
- const job = this.jobs.get(jobId);
174
- if (!job) {
175
- return {
176
- success: false,
177
- error: `Job not found: ${jobId}`
178
- };
179
- }
180
- if (job.getStatus() !== types_1.JobStatus.PAUSED) {
181
- return {
182
- success: false,
183
- error: `Job is not paused: ${jobId}`
184
- };
185
- }
186
- job.resume();
187
- this.logger.info('Job resumed', { jobId });
188
- return { success: true };
189
- }
190
- /**
191
- * Get a scheduled job by ID
192
- *
193
- * @param jobId - Job ID
194
- * @returns Job instance or undefined
195
- */
196
- getJob(jobId) {
197
- return this.jobs.get(jobId);
198
- }
199
- /**
200
- * Get all scheduled jobs
201
- *
202
- * @returns Array of all jobs
203
- */
204
- getAllJobs() {
205
- return Array.from(this.jobs.values());
206
- }
207
- /**
208
- * Get jobs by status
209
- *
210
- * @param status - Job status to filter by
211
- * @returns Array of jobs with the specified status
212
- */
213
- getJobsByStatus(status) {
214
- return Array.from(this.jobs.values()).filter((job) => job.getStatus() === status);
215
- }
216
- /**
217
- * Get job statistics
218
- *
219
- * @param jobId - Job ID
220
- * @returns Job statistics or undefined
221
- */
222
- getJobStatistics(jobId) {
223
- const job = this.jobs.get(jobId);
224
- return job?.getStatistics();
225
- }
226
- /**
227
- * Cancel all jobs
228
- */
229
- cancelAll() {
230
- const jobIds = Array.from(this.jobs.keys());
231
- for (const jobId of jobIds) {
232
- this.cancel(jobId);
233
- }
234
- this.logger.info('All jobs cancelled', { count: jobIds.length });
235
- }
236
- /**
237
- * Get scheduler statistics
238
- *
239
- * @returns Overall scheduler statistics
240
- */
241
- getSchedulerStatistics() {
242
- const jobs = Array.from(this.jobs.values());
243
- return {
244
- totalJobs: jobs.length,
245
- activeJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.SCHEDULED ||
246
- j.getStatus() === types_1.JobStatus.RUNNING).length,
247
- pausedJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.PAUSED).length,
248
- completedJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.COMPLETED)
249
- .length,
250
- failedJobs: jobs.filter((j) => j.getStatus() === types_1.JobStatus.FAILED).length
251
- };
252
- }
253
- /**
254
- * Validate cron expression
255
- *
256
- * @param cronExpression - Cron expression to validate
257
- * @returns Result indicating if expression is valid
258
- */
259
- validateCronExpression(cronExpression) {
260
- try {
261
- (0, cron_parser_1.parseExpression)(cronExpression);
262
- return { success: true };
263
- }
264
- catch (error) {
265
- const errorMessage = error instanceof Error ? error.message : String(error);
266
- return {
267
- success: false,
268
- error: `Invalid cron expression: ${errorMessage}`
269
- };
270
- }
271
- }
272
- /**
273
- * Generate unique job ID
274
- */
275
- generateJobId() {
276
- const id = `job-${this.nextJobId}`;
277
- this.nextJobId++;
278
- return id;
279
- }
280
- /**
281
- * Shutdown scheduler and cancel all jobs
282
- */
283
- shutdown() {
284
- this.logger.info('Shutting down scheduler');
285
- this.cancelAll();
286
- this.logger.info('Scheduler shutdown complete');
287
- }
288
- }
289
- exports.JobScheduler = JobScheduler;
290
- /**
291
- * Create a new job scheduler instance
292
- *
293
- * @param config - Scheduler configuration
294
- * @returns JobScheduler instance
295
- */
296
- function createJobScheduler(config) {
297
- return new JobScheduler(config);
298
- }
@@ -1,70 +0,0 @@
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
- }
@@ -1,284 +0,0 @@
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
- config;
18
- status;
19
- executions;
20
- timer;
21
- logger;
22
- currentRetries = 0;
23
- constructor(config, logger) {
24
- this.config = config;
25
- this.status = types_1.JobStatus.SCHEDULED;
26
- this.executions = [];
27
- this.logger = logger;
28
- }
29
- /**
30
- * Get job ID
31
- */
32
- getId() {
33
- return this.config.id;
34
- }
35
- /**
36
- * Get job name
37
- */
38
- getName() {
39
- return this.config.name || this.config.id;
40
- }
41
- /**
42
- * Get job type
43
- */
44
- getType() {
45
- return this.config.type;
46
- }
47
- /**
48
- * Get job status
49
- */
50
- getStatus() {
51
- return this.status;
52
- }
53
- /**
54
- * Get job configuration
55
- */
56
- getConfig() {
57
- return Object.freeze({ ...this.config });
58
- }
59
- /**
60
- * Get job execution history
61
- */
62
- getExecutions() {
63
- return Object.freeze([...this.executions]);
64
- }
65
- /**
66
- * Get job statistics
67
- */
68
- getStatistics() {
69
- const successfulExecutions = this.executions.filter((e) => e.status === types_1.JobStatus.COMPLETED);
70
- const failedExecutions = this.executions.filter((e) => e.status === types_1.JobStatus.FAILED);
71
- const totalDuration = this.executions.reduce((sum, e) => sum + (e.duration || 0), 0);
72
- const lastExecution = this.executions.length > 0
73
- ? this.executions[this.executions.length - 1].startTime
74
- : undefined;
75
- let nextExecution;
76
- if (this.config.type === types_1.JobType.RECURRING && this.config.cronExpression) {
77
- try {
78
- const interval = (0, cron_parser_1.parseExpression)(this.config.cronExpression);
79
- nextExecution = interval.next().toDate();
80
- }
81
- catch (error) {
82
- this.logger.error('Failed to calculate next execution');
83
- }
84
- }
85
- else if (this.config.type === types_1.JobType.ONE_TIME && this.config.scheduledTime) {
86
- nextExecution = this.config.scheduledTime;
87
- }
88
- return {
89
- totalExecutions: this.executions.length,
90
- successfulExecutions: successfulExecutions.length,
91
- failedExecutions: failedExecutions.length,
92
- averageDuration: this.executions.length > 0 ? totalDuration / this.executions.length : 0,
93
- lastExecution,
94
- nextExecution
95
- };
96
- }
97
- /**
98
- * Start job execution
99
- */
100
- start() {
101
- if (this.status === types_1.JobStatus.RUNNING) {
102
- this.logger.warn('Job is already running', { jobId: this.config.id });
103
- return;
104
- }
105
- if (this.status === types_1.JobStatus.CANCELLED) {
106
- this.logger.warn('Cannot start cancelled job', { jobId: this.config.id });
107
- return;
108
- }
109
- this.status = types_1.JobStatus.SCHEDULED;
110
- if (this.config.type === types_1.JobType.RECURRING) {
111
- if (!this.config.cronExpression) {
112
- throw new Error('Cron expression is required for recurring jobs');
113
- }
114
- this.scheduleRecurring();
115
- }
116
- else if (this.config.type === types_1.JobType.ONE_TIME) {
117
- if (!this.config.scheduledTime) {
118
- throw new Error('Scheduled time is required for one-time jobs');
119
- }
120
- this.scheduleOneTime();
121
- }
122
- this.logger.info('Job started', {
123
- jobId: this.config.id,
124
- type: this.config.type,
125
- name: this.config.name
126
- });
127
- }
128
- /**
129
- * Pause job execution
130
- */
131
- pause() {
132
- if (this.status === types_1.JobStatus.RUNNING) {
133
- this.logger.warn('Cannot pause running job', { jobId: this.config.id });
134
- return;
135
- }
136
- if (this.timer) {
137
- clearTimeout(this.timer);
138
- this.timer = undefined;
139
- }
140
- this.status = types_1.JobStatus.PAUSED;
141
- this.logger.info('Job paused', { jobId: this.config.id });
142
- }
143
- /**
144
- * Resume job execution
145
- */
146
- resume() {
147
- if (this.status !== types_1.JobStatus.PAUSED) {
148
- this.logger.warn('Job is not paused', { jobId: this.config.id });
149
- return;
150
- }
151
- this.start();
152
- this.logger.info('Job resumed', { jobId: this.config.id });
153
- }
154
- /**
155
- * Cancel job execution
156
- */
157
- cancel() {
158
- if (this.timer) {
159
- clearTimeout(this.timer);
160
- this.timer = undefined;
161
- }
162
- this.status = types_1.JobStatus.CANCELLED;
163
- this.logger.info('Job cancelled', { jobId: this.config.id });
164
- }
165
- /**
166
- * Execute job handler
167
- */
168
- async executeJob() {
169
- const executionId = `${this.config.id}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
170
- const startTime = new Date();
171
- const execution = {
172
- executionId,
173
- jobId: this.config.id,
174
- startTime,
175
- status: types_1.JobStatus.RUNNING
176
- };
177
- this.executions.push(execution);
178
- this.status = types_1.JobStatus.RUNNING;
179
- this.logger.info('Job execution started', {
180
- executionId,
181
- jobId: this.config.id,
182
- name: this.config.name
183
- });
184
- try {
185
- await this.config.handler();
186
- const endTime = new Date();
187
- execution.endTime = endTime;
188
- execution.status = types_1.JobStatus.COMPLETED;
189
- execution.duration = endTime.getTime() - startTime.getTime();
190
- this.currentRetries = 0;
191
- this.logger.info('Job execution completed', {
192
- executionId,
193
- jobId: this.config.id,
194
- duration: execution.duration
195
- });
196
- }
197
- catch (error) {
198
- const endTime = new Date();
199
- execution.endTime = endTime;
200
- execution.status = types_1.JobStatus.FAILED;
201
- execution.duration = endTime.getTime() - startTime.getTime();
202
- execution.error = error instanceof Error ? error.message : String(error);
203
- this.logger.error('Job execution failed');
204
- // Handle retries
205
- if (this.config.maxRetries &&
206
- this.currentRetries < this.config.maxRetries) {
207
- this.currentRetries++;
208
- const retryDelay = this.config.retryDelay || 5000;
209
- this.logger.info('Scheduling job retry', {
210
- jobId: this.config.id,
211
- retry: this.currentRetries,
212
- maxRetries: this.config.maxRetries,
213
- delay: retryDelay
214
- });
215
- setTimeout(() => {
216
- void this.executeJob();
217
- }, retryDelay);
218
- }
219
- }
220
- finally {
221
- this.status = types_1.JobStatus.SCHEDULED;
222
- // Schedule next execution for recurring jobs
223
- if (this.config.type === types_1.JobType.RECURRING &&
224
- this.status === types_1.JobStatus.SCHEDULED) {
225
- this.scheduleRecurring();
226
- }
227
- else if (this.config.type === types_1.JobType.ONE_TIME) {
228
- this.status = types_1.JobStatus.COMPLETED;
229
- this.logger.info('One-time job completed');
230
- }
231
- }
232
- }
233
- /**
234
- * Schedule recurring job
235
- */
236
- scheduleRecurring() {
237
- if (!this.config.cronExpression) {
238
- throw new Error('Cron expression is required for recurring jobs');
239
- }
240
- try {
241
- const interval = (0, cron_parser_1.parseExpression)(this.config.cronExpression);
242
- const nextRun = interval.next().toDate();
243
- const delay = nextRun.getTime() - Date.now();
244
- this.timer = setTimeout(() => {
245
- void this.executeJob();
246
- }, delay);
247
- this.logger.debug('Recurring job scheduled', {
248
- jobId: this.config.id,
249
- nextRun: nextRun.toISOString(),
250
- delay
251
- });
252
- }
253
- catch (error) {
254
- this.logger.error('Failed to schedule recurring job');
255
- throw error;
256
- }
257
- }
258
- /**
259
- * Schedule one-time job
260
- */
261
- scheduleOneTime() {
262
- if (!this.config.scheduledTime) {
263
- throw new Error('Scheduled time is required for one-time jobs');
264
- }
265
- const delay = this.config.scheduledTime.getTime() - Date.now();
266
- if (delay < 0) {
267
- this.logger.warn('Scheduled time is in the past, executing immediately', {
268
- jobId: this.config.id,
269
- scheduledTime: this.config.scheduledTime.toISOString()
270
- });
271
- void this.executeJob();
272
- return;
273
- }
274
- this.timer = setTimeout(() => {
275
- void this.executeJob();
276
- }, delay);
277
- this.logger.debug('One-time job scheduled', {
278
- jobId: this.config.id,
279
- scheduledTime: this.config.scheduledTime.toISOString(),
280
- delay
281
- });
282
- }
283
- }
284
- exports.ScheduledJob = ScheduledJob;
package/dist/errors.d.ts DELETED
@@ -1,11 +0,0 @@
1
- export type JobSchedulerErrorCode = 'JOB_SCHEDULER_ERROR' | 'INVALID_INPUT' | 'OPERATION_FAILED';
2
- export interface JobSchedulerErrorOptions {
3
- cause?: Error;
4
- code?: JobSchedulerErrorCode;
5
- context?: Record<string, unknown>;
6
- }
7
- export declare class JobSchedulerError extends Error {
8
- readonly code: JobSchedulerErrorCode;
9
- readonly context?: Record<string, unknown>;
10
- constructor(message: string, options?: JobSchedulerErrorOptions);
11
- }
package/dist/errors.js DELETED
@@ -1,24 +0,0 @@
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.JobSchedulerError = void 0;
11
- class JobSchedulerError extends Error {
12
- code;
13
- context;
14
- constructor(message, options) {
15
- super(message, options?.cause ? { cause: options.cause } : undefined);
16
- this.name = 'JobSchedulerError';
17
- this.code = options?.code ?? 'JOB_SCHEDULER_ERROR';
18
- if (options?.context !== undefined) {
19
- this.context = options.context;
20
- }
21
- Error.captureStackTrace?.(this, this.constructor);
22
- }
23
- }
24
- exports.JobSchedulerError = JobSchedulerError;
package/dist/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export { JobSchedulerError, type JobSchedulerErrorCode, type JobSchedulerErrorOptions, } from './errors';
2
- export { JobScheduler, createJobScheduler } from './JobScheduler';
3
- export { ScheduledJob } from './ScheduledJob';
4
- export { JobStatus, JobType, JobHandler, JobExecution, ScheduledJobConfig, JobSchedulerConfig, JobSchedulerResult, JobStatistics } from './types';
package/dist/index.js DELETED
@@ -1,20 +0,0 @@
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 = exports.JobSchedulerError = void 0;
11
- var errors_1 = require("./errors");
12
- Object.defineProperty(exports, "JobSchedulerError", { enumerable: true, get: function () { return errors_1.JobSchedulerError; } });
13
- var JobScheduler_1 = require("./JobScheduler");
14
- Object.defineProperty(exports, "JobScheduler", { enumerable: true, get: function () { return JobScheduler_1.JobScheduler; } });
15
- Object.defineProperty(exports, "createJobScheduler", { enumerable: true, get: function () { return JobScheduler_1.createJobScheduler; } });
16
- var ScheduledJob_1 = require("./ScheduledJob");
17
- Object.defineProperty(exports, "ScheduledJob", { enumerable: true, get: function () { return ScheduledJob_1.ScheduledJob; } });
18
- var types_1 = require("./types");
19
- Object.defineProperty(exports, "JobStatus", { enumerable: true, get: function () { return types_1.JobStatus; } });
20
- Object.defineProperty(exports, "JobType", { enumerable: true, get: function () { return types_1.JobType; } });
package/dist/types.d.ts DELETED
@@ -1,81 +0,0 @@
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 DELETED
@@ -1,30 +0,0 @@
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 = {}));