@navios/schedule 0.9.0 → 1.0.0-alpha.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/CHANGELOG.md +15 -0
- package/dist/src/legacy-compat/decorators/cron.decorator.d.mts +31 -0
- package/dist/src/legacy-compat/decorators/cron.decorator.d.mts.map +1 -0
- package/dist/src/legacy-compat/decorators/index.d.mts +3 -0
- package/dist/src/legacy-compat/decorators/index.d.mts.map +1 -0
- package/dist/src/legacy-compat/decorators/schedulable.decorator.d.mts +36 -0
- package/dist/src/legacy-compat/decorators/schedulable.decorator.d.mts.map +1 -0
- package/dist/src/legacy-compat/index.d.mts +26 -0
- package/dist/src/legacy-compat/index.d.mts.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/lib/index.cjs +12 -620
- package/lib/index.d.cts +2 -232
- package/lib/index.d.cts.map +1 -1
- package/lib/index.d.mts +2 -232
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +2 -610
- package/lib/legacy-compat/index.cjs +98 -0
- package/lib/legacy-compat/index.cjs.map +1 -0
- package/lib/legacy-compat/index.d.cts +73 -0
- package/lib/legacy-compat/index.d.cts.map +1 -0
- package/lib/legacy-compat/index.d.mts +73 -0
- package/lib/legacy-compat/index.d.mts.map +1 -0
- package/lib/legacy-compat/index.mjs +73 -0
- package/lib/legacy-compat/index.mjs.map +1 -0
- package/lib/scheduler.service-BinyHmuL.cjs +676 -0
- package/lib/scheduler.service-BinyHmuL.cjs.map +1 -0
- package/lib/scheduler.service-Ccvw4fsy.d.cts +236 -0
- package/lib/scheduler.service-Ccvw4fsy.d.cts.map +1 -0
- package/lib/scheduler.service-DkyiR8iY.mjs +611 -0
- package/lib/scheduler.service-DkyiR8iY.mjs.map +1 -0
- package/lib/scheduler.service-pFh29qTy.d.mts +236 -0
- package/lib/scheduler.service-pFh29qTy.d.mts.map +1 -0
- package/package.json +13 -3
- package/src/legacy-compat/decorators/cron.decorator.mts +58 -0
- package/src/legacy-compat/decorators/index.mts +2 -0
- package/src/legacy-compat/decorators/schedulable.decorator.mts +47 -0
- package/src/legacy-compat/index.mts +41 -0
- package/tsdown.config.mts +1 -1
- package/lib/index.cjs.map +0 -1
- package/lib/index.mjs.map +0 -1
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { ClassType } from "@navios/core";
|
|
2
|
+
import { CronJob, CronJobParams } from "cron";
|
|
3
|
+
|
|
4
|
+
//#region src/decorators/cron.decorator.d.mts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Options for configuring a cron job.
|
|
8
|
+
*
|
|
9
|
+
* @public
|
|
10
|
+
*/
|
|
11
|
+
interface CronOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Whether the job should be disabled by default.
|
|
14
|
+
* Disabled jobs won't start automatically but can be manually started later.
|
|
15
|
+
*
|
|
16
|
+
* @default false
|
|
17
|
+
*/
|
|
18
|
+
disabled?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Decorator that marks a method to run on a cron schedule.
|
|
22
|
+
*
|
|
23
|
+
* The method must be in a class decorated with `@Schedulable()`.
|
|
24
|
+
* The method will be automatically executed according to the provided cron expression.
|
|
25
|
+
*
|
|
26
|
+
* @param cronTime - Cron expression (5 or 6 fields) or a pre-defined Schedule constant
|
|
27
|
+
* @param options - Optional configuration for the cron job
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* @Schedulable()
|
|
32
|
+
* class TaskService {
|
|
33
|
+
* // Run daily at midnight
|
|
34
|
+
* @Cron('0 0 * * *')
|
|
35
|
+
* async dailyTask() {
|
|
36
|
+
* console.log('Running daily task')
|
|
37
|
+
* }
|
|
38
|
+
*
|
|
39
|
+
* // Use pre-defined schedule
|
|
40
|
+
* @Cron(Schedule.EveryFiveMinutes)
|
|
41
|
+
* async frequentTask() {
|
|
42
|
+
* console.log('Running every 5 minutes')
|
|
43
|
+
* }
|
|
44
|
+
*
|
|
45
|
+
* // Disabled job (won't start automatically)
|
|
46
|
+
* @Cron('0 2 * * *', { disabled: true })
|
|
47
|
+
* async maintenanceTask() {
|
|
48
|
+
* console.log('Maintenance task')
|
|
49
|
+
* }
|
|
50
|
+
* }
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* @throws {Error} If applied to something other than a method
|
|
54
|
+
*
|
|
55
|
+
* @public
|
|
56
|
+
*/
|
|
57
|
+
declare function Cron(cronTime: CronJobParams['cronTime'], options?: CronOptions): (target: () => Promise<void>, context: ClassMethodDecoratorContext) => () => Promise<void>;
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/metadata/cron.metadata.d.mts
|
|
60
|
+
declare const CronMetadataKey: unique symbol;
|
|
61
|
+
interface CronMetadata {
|
|
62
|
+
classMethod: string;
|
|
63
|
+
cronTime: CronJobParams['cronTime'] | null;
|
|
64
|
+
disabled: boolean;
|
|
65
|
+
}
|
|
66
|
+
declare function getAllCronMetadata(context: ClassMethodDecoratorContext | ClassDecoratorContext): Set<CronMetadata>;
|
|
67
|
+
declare function getCronMetadata(target: Function, context: ClassMethodDecoratorContext): CronMetadata;
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/metadata/schedule.metadata.d.mts
|
|
70
|
+
declare const ScheduleMetadataKey: unique symbol;
|
|
71
|
+
interface ScheduleMetadata {
|
|
72
|
+
name: string;
|
|
73
|
+
jobs: Set<CronMetadata>;
|
|
74
|
+
}
|
|
75
|
+
declare function getScheduleMetadata(target: ClassType, context: ClassDecoratorContext): ScheduleMetadata;
|
|
76
|
+
declare function extractScheduleMetadata(target: ClassType): ScheduleMetadata;
|
|
77
|
+
declare function hasScheduleMetadata(target: ClassType): boolean;
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/cron.constants.d.mts
|
|
80
|
+
/**
|
|
81
|
+
* Pre-defined cron schedule constants for common scheduling patterns.
|
|
82
|
+
*
|
|
83
|
+
* These constants provide convenient shortcuts for frequently used cron expressions,
|
|
84
|
+
* making it easier to schedule jobs without manually writing cron expressions.
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```typescript
|
|
88
|
+
* import { Schedule } from '@navios/schedule'
|
|
89
|
+
*
|
|
90
|
+
* @Schedulable()
|
|
91
|
+
* class TaskService {
|
|
92
|
+
* @Cron(Schedule.EveryMinute)
|
|
93
|
+
* async everyMinute() {}
|
|
94
|
+
*
|
|
95
|
+
* @Cron(Schedule.EveryHour)
|
|
96
|
+
* async hourly() {}
|
|
97
|
+
*
|
|
98
|
+
* @Cron(Schedule.EveryDay)
|
|
99
|
+
* async daily() {}
|
|
100
|
+
* }
|
|
101
|
+
* ```
|
|
102
|
+
*
|
|
103
|
+
* @public
|
|
104
|
+
*/
|
|
105
|
+
declare enum Schedule {
|
|
106
|
+
EveryMinute = "*/1 * * * *",
|
|
107
|
+
EveryFiveMinutes = "*/5 * * * *",
|
|
108
|
+
EveryTenMinutes = "*/10 * * * *",
|
|
109
|
+
EveryFifteenMinutes = "*/15 * * * *",
|
|
110
|
+
EveryThirtyMinutes = "*/30 * * * *",
|
|
111
|
+
EveryHour = "0 * * * *",
|
|
112
|
+
EveryTwoHours = "0 */2 * * *",
|
|
113
|
+
EveryThreeHours = "0 */3 * * *",
|
|
114
|
+
EveryFourHours = "0 */4 * * *",
|
|
115
|
+
EverySixHours = "0 */6 * * *",
|
|
116
|
+
EveryTwelveHours = "0 */12 * * *",
|
|
117
|
+
EveryDay = "0 0 * * *",
|
|
118
|
+
EveryWeek = "0 0 * * 0",
|
|
119
|
+
EveryMonth = "0 0 1 * *",
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/scheduler.service.d.mts
|
|
123
|
+
/**
|
|
124
|
+
* Service responsible for managing and executing scheduled cron jobs.
|
|
125
|
+
*
|
|
126
|
+
* The SchedulerService registers schedulable services decorated with `@Schedulable()`
|
|
127
|
+
* and automatically starts their cron jobs based on the `@Cron()` decorator configuration.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```typescript
|
|
131
|
+
* import { inject, Injectable } from '@navios/core'
|
|
132
|
+
* import { SchedulerService } from '@navios/schedule'
|
|
133
|
+
*
|
|
134
|
+
* @Injectable()
|
|
135
|
+
* class AppModule {
|
|
136
|
+
* private readonly scheduler = inject(SchedulerService)
|
|
137
|
+
*
|
|
138
|
+
* async onModuleInit() {
|
|
139
|
+
* this.scheduler.register(MySchedulableService)
|
|
140
|
+
* }
|
|
141
|
+
* }
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* @public
|
|
145
|
+
*/
|
|
146
|
+
declare class SchedulerService {
|
|
147
|
+
private readonly logger;
|
|
148
|
+
private readonly container;
|
|
149
|
+
private readonly jobs;
|
|
150
|
+
/**
|
|
151
|
+
* Registers a schedulable service and starts all its cron jobs.
|
|
152
|
+
*
|
|
153
|
+
* The service must be decorated with `@Schedulable()` and contain methods
|
|
154
|
+
* decorated with `@Cron()` to be registered successfully.
|
|
155
|
+
*
|
|
156
|
+
* @param service - The schedulable service class to register
|
|
157
|
+
* @throws {Error} If the service is not decorated with `@Schedulable()`
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```typescript
|
|
161
|
+
* @Schedulable()
|
|
162
|
+
* class TaskService {
|
|
163
|
+
* @Cron('0 0 * * *')
|
|
164
|
+
* async dailyTask() {
|
|
165
|
+
* // Runs daily at midnight
|
|
166
|
+
* }
|
|
167
|
+
* }
|
|
168
|
+
*
|
|
169
|
+
* schedulerService.register(TaskService)
|
|
170
|
+
* ```
|
|
171
|
+
*
|
|
172
|
+
* @public
|
|
173
|
+
*/
|
|
174
|
+
register(service: ClassType): void;
|
|
175
|
+
/**
|
|
176
|
+
* Retrieves a specific cron job instance for a method in a schedulable service.
|
|
177
|
+
*
|
|
178
|
+
* @param service - The schedulable service class
|
|
179
|
+
* @param method - The name of the method decorated with `@Cron()`
|
|
180
|
+
* @returns The CronJob instance if found, undefined otherwise
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* ```typescript
|
|
184
|
+
* const job = schedulerService.getJob(TaskService, 'dailyTask')
|
|
185
|
+
* if (job) {
|
|
186
|
+
* console.log('Job is active:', job.isActive)
|
|
187
|
+
* job.start() // Manually start the job
|
|
188
|
+
* job.stop() // Manually stop the job
|
|
189
|
+
* }
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* @public
|
|
193
|
+
*/
|
|
194
|
+
getJob<T extends ClassType>(service: T, method: keyof InstanceType<T>): CronJob | undefined;
|
|
195
|
+
private registerJobs;
|
|
196
|
+
/**
|
|
197
|
+
* Starts all registered cron jobs that are currently inactive.
|
|
198
|
+
*
|
|
199
|
+
* Only jobs that are not already active will be started. This method
|
|
200
|
+
* is useful for resuming all jobs after calling `stopAll()`.
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* ```typescript
|
|
204
|
+
* // Stop all jobs
|
|
205
|
+
* schedulerService.stopAll()
|
|
206
|
+
*
|
|
207
|
+
* // Later, resume all jobs
|
|
208
|
+
* schedulerService.startAll()
|
|
209
|
+
* ```
|
|
210
|
+
*
|
|
211
|
+
* @public
|
|
212
|
+
*/
|
|
213
|
+
startAll(): void;
|
|
214
|
+
/**
|
|
215
|
+
* Stops all registered cron jobs that are currently active.
|
|
216
|
+
*
|
|
217
|
+
* Only jobs that are currently active will be stopped. This method
|
|
218
|
+
* is useful for pausing all scheduled tasks, for example during
|
|
219
|
+
* application shutdown or maintenance.
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```typescript
|
|
223
|
+
* // Pause all scheduled jobs
|
|
224
|
+
* schedulerService.stopAll()
|
|
225
|
+
*
|
|
226
|
+
* // Jobs can be resumed later with startAll()
|
|
227
|
+
* schedulerService.startAll()
|
|
228
|
+
* ```
|
|
229
|
+
*
|
|
230
|
+
* @public
|
|
231
|
+
*/
|
|
232
|
+
stopAll(): void;
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
export { extractScheduleMetadata as a, CronMetadata as c, getCronMetadata as d, Cron as f, ScheduleMetadataKey as i, CronMetadataKey as l, Schedule as n, getScheduleMetadata as o, CronOptions as p, ScheduleMetadata as r, hasScheduleMetadata as s, SchedulerService as t, getAllCronMetadata as u };
|
|
236
|
+
//# sourceMappingURL=scheduler.service-pFh29qTy.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.service-pFh29qTy.d.mts","names":[],"sources":["../src/decorators/cron.decorator.mts","../src/metadata/cron.metadata.mts","../src/metadata/schedule.metadata.mts","../src/cron.constants.mts","../src/scheduler.service.mts"],"sourcesContent":[],"mappings":";;;;;;;;AASA;AA+CA;AACY,UAhDK,WAAA,CAgDL;EACA;;;;;;;;ACxDZ;AAEA;AAMA;;;;;;AAiBA;;;;;;;;ACrBA;AAEA;AAKA;;;;;AAyBA;AAWA;;;;ACxBA;;;;ACWA;;;;;AAgEkB,iBJ5CF,IAAA,CI4CE,QAAA,EJ3CN,aI2CM,CAAA,UAAA,CAAA,EAAA,OAAA,CAAA,EJ1CN,WI0CM,CAAA,EAAA,CAAA,MAAA,EAAA,GAAA,GJvCA,OIuCA,CAAA,IAAA,CAAA,EAAA,OAAA,EJtCL,2BIsCK,EAAA,GAAA,GAAA,GJvCA,OIuCA,CAAA,IAAA,CAAA;;;cHlGL;UAEI,YAAA;;EDKA,QAAA,ECHL,aDGgB,CAAA,UAAA,CAAA,GAAA,IAAA;EA+CZ,QAAI,EAAA,OAAA;;AAER,iBChDI,kBAAA,CDgDJ,OAAA,EC/CD,2BD+CC,GC/C6B,qBD+C7B,CAAA,EC9CT,GD8CS,CC9CL,YD8CK,CAAA;AAGM,iBClCF,eAAA,CDkCE,MAAA,ECjCR,QDiCQ,EAAA,OAAA,EChCP,2BDgCO,CAAA,EC/Bf,YD+Be;;;cEvDL;UAEI,gBAAA;EFCA,IAAA,EAAA,MAAA;EA+CD,IAAA,EE9CR,GF8CY,CE9CR,YF8CQ,CAAA;;AAER,iBE7CI,mBAAA,CF6CJ,MAAA,EE5CF,SF4CE,EAAA,OAAA,EE3CD,qBF2CC,CAAA,EE1CT,gBF0CS;AAGM,iBEvBF,uBAAA,CFuBE,MAAA,EEvB8B,SFuB9B,CAAA,EEvB0C,gBFuB1C;AACL,iBEbG,mBAAA,CFaH,MAAA,EEb+B,SFa/B,CAAA,EAAA,OAAA;;;;;;;AArDb;AA+CA;;;;;;;;;;ACtDA;AAEA;AAMA;;;;;;AAiBA;;AAEW,aEJC,QAAA;EFKT,WAAA,GAAA,aAAA;EAAY,gBAAA,GAAA,aAAA;;;;ECxBF,SAAA,GAAA,WAAqD;EAEjD,aAAA,GAAA,aAAgB;EAKjB,eAAA,GAAA,aAAmB;EACzB,cAAA,GAAA,aAAA;EACC,aAAA,GAAA,aAAA;EACR,gBAAA,GAAA,cAAA;EAAgB,QAAA,GAAA,WAAA;EAsBH,SAAA,GAAA,WAAA;EAWA,UAAA,GAAA,WAAmB;;;;;;AFxCnC;AA+CA;;;;;;;;;;ACtDA;AAEA;AAMA;;;;;;AAiBA;;AAEW,cGQE,gBAAA,CHRF;EACR,iBAAA,MAAA;EAAY,iBAAA,SAAA;;;;ACxBf;AAEA;AAKA;;;;;AAyBA;AAWA;;;;ACxBA;;;;ACWA;;;;;;EAiEK,QAAA,CAAA,OAAA,EAjCe,SAiCf,CAAA,EAAA,IAAA;EAAO;;;;;;;;;;;;;;;;;;;mBAHO,oBACN,iBACK,aAAa,KAC1B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@navios/schedule",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0-alpha.2",
|
|
4
4
|
"author": {
|
|
5
5
|
"name": "Oleksandr Hanzha",
|
|
6
6
|
"email": "alex@granted.name"
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
},
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"peerDependencies": {
|
|
15
|
-
"@navios/core": "^0.
|
|
15
|
+
"@navios/core": "^1.0.0-alpha.2",
|
|
16
16
|
"zod": "^3.25.0 || ^4.0.0"
|
|
17
17
|
},
|
|
18
18
|
"typings": "./lib/index.d.mts",
|
|
@@ -28,10 +28,20 @@
|
|
|
28
28
|
"types": "./lib/index.d.cts",
|
|
29
29
|
"default": "./lib/index.cjs"
|
|
30
30
|
}
|
|
31
|
+
},
|
|
32
|
+
"./legacy-compat": {
|
|
33
|
+
"import": {
|
|
34
|
+
"types": "./lib/legacy-compat/index.d.mts",
|
|
35
|
+
"default": "./lib/legacy-compat/index.mjs"
|
|
36
|
+
},
|
|
37
|
+
"require": {
|
|
38
|
+
"types": "./lib/legacy-compat/index.d.cts",
|
|
39
|
+
"default": "./lib/legacy-compat/index.cjs"
|
|
40
|
+
}
|
|
31
41
|
}
|
|
32
42
|
},
|
|
33
43
|
"devDependencies": {
|
|
34
|
-
"@navios/core": "^0.
|
|
44
|
+
"@navios/core": "^1.0.0-alpha.2",
|
|
35
45
|
"typescript": "^5.9.3",
|
|
36
46
|
"zod": "^4.2.1"
|
|
37
47
|
},
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { CronJobParams } from 'cron'
|
|
2
|
+
|
|
3
|
+
import { createMethodContext } from '@navios/core/legacy-compat'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
Cron as OriginalCron,
|
|
7
|
+
type CronOptions,
|
|
8
|
+
} from '../../decorators/cron.decorator.mjs'
|
|
9
|
+
|
|
10
|
+
export type { CronOptions }
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Legacy-compatible Cron decorator.
|
|
14
|
+
*
|
|
15
|
+
* Works with TypeScript experimental decorators (legacy API).
|
|
16
|
+
* Marks a method to run on a cron schedule.
|
|
17
|
+
*
|
|
18
|
+
* @param cronTime - Cron expression (5 or 6 fields) or a pre-defined Schedule constant
|
|
19
|
+
* @param options - Optional configuration for the cron job
|
|
20
|
+
* @returns A method decorator compatible with legacy decorator API
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* @Schedulable()
|
|
25
|
+
* class TaskService {
|
|
26
|
+
* @Cron('0 0 * * *')
|
|
27
|
+
* async dailyTask() {
|
|
28
|
+
* console.log('Running daily task')
|
|
29
|
+
* }
|
|
30
|
+
*
|
|
31
|
+
* @Cron(Schedule.EveryFiveMinutes, { disabled: true })
|
|
32
|
+
* async frequentTask() {
|
|
33
|
+
* console.log('Running every 5 minutes')
|
|
34
|
+
* }
|
|
35
|
+
* }
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export function Cron(cronTime: CronJobParams['cronTime'], options?: CronOptions) {
|
|
39
|
+
return function <T extends object>(
|
|
40
|
+
target: T,
|
|
41
|
+
propertyKey: string | symbol,
|
|
42
|
+
descriptor: TypedPropertyDescriptor<() => Promise<void>>,
|
|
43
|
+
): PropertyDescriptor | void {
|
|
44
|
+
if (!descriptor) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
'[Navios] @Cron decorator requires a method descriptor. Make sure experimentalDecorators is enabled.',
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
const context = createMethodContext(target, propertyKey, descriptor)
|
|
50
|
+
const originalDecorator = OriginalCron(cronTime, options)
|
|
51
|
+
// @ts-expect-error - we don't need to type the value
|
|
52
|
+
const result = originalDecorator(descriptor.value, context)
|
|
53
|
+
if (result !== descriptor.value) {
|
|
54
|
+
descriptor.value = result as any
|
|
55
|
+
}
|
|
56
|
+
return descriptor
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { ClassType, Registry } from '@navios/core'
|
|
2
|
+
|
|
3
|
+
import { createClassContext } from '@navios/core/legacy-compat'
|
|
4
|
+
|
|
5
|
+
import { Schedulable as OriginalSchedulable } from '../../decorators/schedulable.decorator.mjs'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Options for the Schedulable decorator.
|
|
9
|
+
*/
|
|
10
|
+
export interface SchedulableOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The registry to register the service with.
|
|
13
|
+
* If not provided, the global registry will be used.
|
|
14
|
+
*/
|
|
15
|
+
registry?: Registry
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Legacy-compatible Schedulable decorator.
|
|
20
|
+
*
|
|
21
|
+
* Works with TypeScript experimental decorators (legacy API).
|
|
22
|
+
* Marks a class as schedulable and makes it injectable.
|
|
23
|
+
*
|
|
24
|
+
* @param options - Optional configuration including the registry to use
|
|
25
|
+
* @returns A class decorator compatible with legacy decorator API
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```typescript
|
|
29
|
+
* @Schedulable()
|
|
30
|
+
* class TaskService {
|
|
31
|
+
* @Cron('0 0 * * *')
|
|
32
|
+
* async dailyTask() {
|
|
33
|
+
* console.log('Running daily task')
|
|
34
|
+
* }
|
|
35
|
+
* }
|
|
36
|
+
*
|
|
37
|
+
* // Register the service
|
|
38
|
+
* schedulerService.register(TaskService)
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export function Schedulable(options: SchedulableOptions = {}) {
|
|
42
|
+
return function (target: ClassType) {
|
|
43
|
+
const context = createClassContext(target)
|
|
44
|
+
const originalDecorator = OriginalSchedulable(options)
|
|
45
|
+
return originalDecorator(target, context)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Legacy-compatible decorators for projects that cannot use Stage 3 decorators.
|
|
3
|
+
*
|
|
4
|
+
* These decorators use the TypeScript experimental decorator API and convert
|
|
5
|
+
* the arguments to Stage 3 format internally.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { Schedulable, Cron, Schedule } from '@navios/schedule/legacy-compat'
|
|
10
|
+
*
|
|
11
|
+
* @Schedulable()
|
|
12
|
+
* class TaskService {
|
|
13
|
+
* @Cron(Schedule.EveryMinute)
|
|
14
|
+
* async everyMinuteTask() {
|
|
15
|
+
* console.log('Running every minute')
|
|
16
|
+
* }
|
|
17
|
+
* }
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// Export legacy-compatible decorators
|
|
22
|
+
export { Cron, Schedulable, type CronOptions, type SchedulableOptions } from './decorators/index.mjs'
|
|
23
|
+
|
|
24
|
+
// Re-export Schedule constants for convenience
|
|
25
|
+
export { Schedule } from '../cron.constants.mjs'
|
|
26
|
+
|
|
27
|
+
// Re-export metadata types and functions (these work with both decorator styles)
|
|
28
|
+
export type { CronMetadata, ScheduleMetadata } from '../metadata/index.mjs'
|
|
29
|
+
export {
|
|
30
|
+
getAllCronMetadata,
|
|
31
|
+
getCronMetadata,
|
|
32
|
+
getScheduleMetadata,
|
|
33
|
+
extractScheduleMetadata,
|
|
34
|
+
hasScheduleMetadata,
|
|
35
|
+
} from '../metadata/index.mjs'
|
|
36
|
+
|
|
37
|
+
// Re-export SchedulerService (works with both decorator styles)
|
|
38
|
+
export { SchedulerService } from '../scheduler.service.mjs'
|
|
39
|
+
|
|
40
|
+
// Re-export context compatibility utilities from core
|
|
41
|
+
export { createClassContext, createMethodContext } from '@navios/core/legacy-compat'
|
package/tsdown.config.mts
CHANGED
package/lib/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["newMetadata: CronMetadata","getAllCronMetadata","ScheduleMetadataKey","Symbol","getScheduleMetadata","target","context","metadata","jobsMetadata","newMetadata","name","jobs","Error","extractScheduleMetadata","hasScheduleMetadata","getCronMetadata","Cron","cronTime","options","target","context","kind","Error","metadata","disabled","globalRegistry","Injectable","getScheduleMetadata","Schedulable","registry","target","context","kind","Error","metadata","Schedule","Container","inject","Injectable","Logger","CronJob","extractScheduleMetadata","hasScheduleMetadata","SchedulerService","logger","context","name","container","jobs","Map","register","service","Error","metadata","debug","registerJobs","getJob","method","jobName","get","job","cronTime","classMethod","self","defaultDisabled","cronJob","from","onTick","instance","error","start","disabled","set","startAll","values","isActive","stopAll","stop"],"sources":["../src/metadata/cron.metadata.mts","../src/metadata/schedule.metadata.mts","../src/decorators/cron.decorator.mts","../src/decorators/schedulable.decorator.mts","../src/cron.constants.mts","../src/scheduler.service.mts"],"sourcesContent":["import type { CronJobParams } from 'cron'\n\nexport const CronMetadataKey = Symbol('CronMetadataKey')\n\nexport interface CronMetadata {\n classMethod: string\n cronTime: CronJobParams['cronTime'] | null\n disabled: boolean\n}\n\nexport function getAllCronMetadata(\n context: ClassMethodDecoratorContext | ClassDecoratorContext,\n): Set<CronMetadata> {\n if (context.metadata) {\n const metadata = context.metadata[CronMetadataKey] as\n | Set<CronMetadata>\n | undefined\n if (metadata) {\n return metadata\n } else {\n context.metadata[CronMetadataKey] = new Set<CronMetadata>()\n return context.metadata[CronMetadataKey] as Set<CronMetadata>\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n\nexport function getCronMetadata(\n target: Function,\n context: ClassMethodDecoratorContext,\n): CronMetadata {\n if (context.metadata) {\n const metadata = getAllCronMetadata(context)\n if (metadata) {\n const endpointMetadata = Array.from(metadata).find(\n (item) => item.classMethod === target.name,\n )\n if (endpointMetadata) {\n return endpointMetadata\n } else {\n const newMetadata: CronMetadata = {\n classMethod: target.name,\n cronTime: null,\n disabled: false,\n }\n metadata.add(newMetadata)\n return newMetadata\n }\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n","import type { ClassType } from '@navios/core'\n\nimport type { CronMetadata } from './cron.metadata.mjs'\n\nimport { getAllCronMetadata } from './cron.metadata.mjs'\n\nexport const ScheduleMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ScheduleMetadata {\n name: string\n jobs: Set<CronMetadata>\n}\n\nexport function getScheduleMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): ScheduleMetadata {\n if (context.metadata) {\n const metadata = context.metadata[ScheduleMetadataKey] as\n | ScheduleMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const jobsMetadata = getAllCronMetadata(context)\n const newMetadata: ScheduleMetadata = {\n name: target.name,\n jobs: jobsMetadata,\n }\n context.metadata[ScheduleMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[ScheduleMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n\nexport function extractScheduleMetadata(target: ClassType): ScheduleMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ScheduleMetadataKey] as ScheduleMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios-Schedule] Controller metadata not found. Make sure to use @Controller decorator.',\n )\n }\n return metadata\n}\n\nexport function hasScheduleMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ScheduleMetadataKey] as ScheduleMetadata | undefined\n\n return !!metadata\n}\n","import type { CronJobParams } from 'cron'\n\nimport { getCronMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a cron job.\n * \n * @public\n */\nexport interface CronOptions {\n /**\n * Whether the job should be disabled by default.\n * Disabled jobs won't start automatically but can be manually started later.\n * \n * @default false\n */\n disabled?: boolean\n}\n\n/**\n * Decorator that marks a method to run on a cron schedule.\n * \n * The method must be in a class decorated with `@Schedulable()`.\n * The method will be automatically executed according to the provided cron expression.\n * \n * @param cronTime - Cron expression (5 or 6 fields) or a pre-defined Schedule constant\n * @param options - Optional configuration for the cron job\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * // Run daily at midnight\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * console.log('Running daily task')\n * }\n * \n * // Use pre-defined schedule\n * @Cron(Schedule.EveryFiveMinutes)\n * async frequentTask() {\n * console.log('Running every 5 minutes')\n * }\n * \n * // Disabled job (won't start automatically)\n * @Cron('0 2 * * *', { disabled: true })\n * async maintenanceTask() {\n * console.log('Maintenance task')\n * }\n * }\n * ```\n * \n * @throws {Error} If applied to something other than a method\n * \n * @public\n */\nexport function Cron(\n cronTime: CronJobParams['cronTime'],\n options?: CronOptions,\n) {\n return (\n target: () => Promise<void>,\n context: ClassMethodDecoratorContext,\n ) => {\n if (context.kind !== 'method') {\n throw new Error(\n `Cron can only be applied to methods, not ${context.kind}`,\n )\n }\n if (context.metadata) {\n const metadata = getCronMetadata(target, context)\n metadata.cronTime = cronTime\n metadata.disabled = options?.disabled ?? false\n }\n return target\n }\n}\n","import type { ClassType } from '@navios/core'\n\nimport { globalRegistry, Injectable, Registry } from '@navios/core'\n\nimport { getScheduleMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that marks a class as schedulable and makes it injectable.\n *\n * Classes decorated with `@Schedulable()` can contain methods decorated with `@Cron()`\n * that will be automatically scheduled and executed. This decorator also applies\n * the `@Injectable()` decorator, making the class available for dependency injection.\n *\n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * // This will run daily at midnight\n * }\n * }\n *\n * // Register the service\n * schedulerService.register(TaskService)\n * ```\n *\n * @throws {Error} If applied to something other than a class\n *\n * @public\n */\nexport function Schedulable({ registry }: { registry?: Registry } = {}) {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error(\n `SchedulableDecorator can only be applied to classes, not ${context.kind}`,\n )\n }\n if (context.metadata) {\n getScheduleMetadata(target, context)\n }\n return Injectable({ registry: registry ?? globalRegistry })(target, context)\n }\n}\n","/**\n * Pre-defined cron schedule constants for common scheduling patterns.\n *\n * These constants provide convenient shortcuts for frequently used cron expressions,\n * making it easier to schedule jobs without manually writing cron expressions.\n *\n * @example\n * ```typescript\n * import { Schedule } from '@navios/schedule'\n *\n * @Schedulable()\n * class TaskService {\n * @Cron(Schedule.EveryMinute)\n * async everyMinute() {}\n *\n * @Cron(Schedule.EveryHour)\n * async hourly() {}\n *\n * @Cron(Schedule.EveryDay)\n * async daily() {}\n * }\n * ```\n *\n * @public\n */\nexport enum Schedule {\n EveryMinute = '*/1 * * * *',\n EveryFiveMinutes = '*/5 * * * *',\n EveryTenMinutes = '*/10 * * * *',\n EveryFifteenMinutes = '*/15 * * * *',\n EveryThirtyMinutes = '*/30 * * * *',\n EveryHour = '0 * * * *',\n EveryTwoHours = '0 */2 * * *',\n EveryThreeHours = '0 */3 * * *',\n EveryFourHours = '0 */4 * * *',\n EverySixHours = '0 */6 * * *',\n EveryTwelveHours = '0 */12 * * *',\n EveryDay = '0 0 * * *',\n EveryWeek = '0 0 * * 0',\n EveryMonth = '0 0 1 * *',\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Container, inject, Injectable, Logger } from '@navios/core'\n\nimport { CronJob } from 'cron'\n\nimport type { ScheduleMetadata } from './metadata/index.mjs'\n\nimport {\n extractScheduleMetadata,\n hasScheduleMetadata,\n} from './metadata/index.mjs'\n\n/**\n * Service responsible for managing and executing scheduled cron jobs.\n * \n * The SchedulerService registers schedulable services decorated with `@Schedulable()`\n * and automatically starts their cron jobs based on the `@Cron()` decorator configuration.\n * \n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/core'\n * import { SchedulerService } from '@navios/schedule'\n * \n * @Injectable()\n * class AppModule {\n * private readonly scheduler = inject(SchedulerService)\n * \n * async onModuleInit() {\n * this.scheduler.register(MySchedulableService)\n * }\n * }\n * ```\n * \n * @public\n */\n@Injectable()\nexport class SchedulerService {\n private readonly logger = inject(Logger, {\n context: SchedulerService.name,\n })\n private readonly container = inject(Container)\n private readonly jobs: Map<string, CronJob> = new Map()\n\n /**\n * Registers a schedulable service and starts all its cron jobs.\n * \n * The service must be decorated with `@Schedulable()` and contain methods\n * decorated with `@Cron()` to be registered successfully.\n * \n * @param service - The schedulable service class to register\n * @throws {Error} If the service is not decorated with `@Schedulable()`\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * // Runs daily at midnight\n * }\n * }\n * \n * schedulerService.register(TaskService)\n * ```\n * \n * @public\n */\n register(service: ClassType) {\n if (!hasScheduleMetadata(service)) {\n throw new Error(\n `[Navios-Schedule] Service ${service.name} is not schedulable. Make sure to use @Schedulable decorator.`,\n )\n }\n const metadata = extractScheduleMetadata(service)\n this.logger.debug('Scheduling service', metadata.name)\n this.registerJobs(service, metadata)\n }\n\n /**\n * Retrieves a specific cron job instance for a method in a schedulable service.\n * \n * @param service - The schedulable service class\n * @param method - The name of the method decorated with `@Cron()`\n * @returns The CronJob instance if found, undefined otherwise\n * \n * @example\n * ```typescript\n * const job = schedulerService.getJob(TaskService, 'dailyTask')\n * if (job) {\n * console.log('Job is active:', job.isActive)\n * job.start() // Manually start the job\n * job.stop() // Manually stop the job\n * }\n * ```\n * \n * @public\n */\n getJob<T extends ClassType>(\n service: T,\n method: keyof InstanceType<T>,\n ): CronJob | undefined {\n const metadata = extractScheduleMetadata(service)\n const jobName = `${metadata.name}.${method as string}()`\n return this.jobs.get(jobName)\n }\n\n private registerJobs(service: ClassType, metadata: ScheduleMetadata) {\n const jobs = metadata.jobs\n for (const job of jobs) {\n if (!job.cronTime) {\n this.logger.debug('Skipping job', job.classMethod)\n continue\n }\n const name = `${metadata.name}.${job.classMethod}()`\n const self = this\n const defaultDisabled = false\n const cronJob = CronJob.from({\n cronTime: job.cronTime,\n name,\n async onTick() {\n try {\n self.logger.debug('Executing job', name)\n const instance = await self.container.get(service)\n await instance[job.classMethod]()\n } catch (error) {\n self.logger.error('Error executing job', name, error)\n }\n },\n start: !(defaultDisabled || job.disabled),\n })\n this.jobs.set(name, cronJob)\n }\n }\n\n /**\n * Starts all registered cron jobs that are currently inactive.\n * \n * Only jobs that are not already active will be started. This method\n * is useful for resuming all jobs after calling `stopAll()`.\n * \n * @example\n * ```typescript\n * // Stop all jobs\n * schedulerService.stopAll()\n * \n * // Later, resume all jobs\n * schedulerService.startAll()\n * ```\n * \n * @public\n */\n startAll() {\n for (const job of this.jobs.values()) {\n if (job.isActive) {\n continue\n }\n job.start()\n }\n }\n\n /**\n * Stops all registered cron jobs that are currently active.\n * \n * Only jobs that are currently active will be stopped. This method\n * is useful for pausing all scheduled tasks, for example during\n * application shutdown or maintenance.\n * \n * @example\n * ```typescript\n * // Pause all scheduled jobs\n * schedulerService.stopAll()\n * \n * // Jobs can be resumed later with startAll()\n * schedulerService.startAll()\n * ```\n * \n * @public\n */\n stopAll() {\n for (const job of this.jobs.values()) {\n if (!job.isActive) {\n continue\n }\n job.stop()\n }\n }\n}\n"],"mappings":";;;;AAEA,MAAa,kBAAkB,OAAO,kBAAkB;AAQxD,SAAgB,mBACd,SACmB;AACnB,KAAI,QAAQ,UAAU;EACpB,MAAM,WAAW,QAAQ,SAAS;AAGlC,MAAI,SACF,QAAO;OACF;AACL,WAAQ,SAAS,mCAAmB,IAAI,KAAmB;AAC3D,UAAO,QAAQ,SAAS;;;AAG5B,OAAM,IAAI,MAAM,uCAAuC;;AAGzD,SAAgB,gBACd,QACA,SACc;AACd,KAAI,QAAQ,UAAU;EACpB,MAAM,WAAW,mBAAmB,QAAQ;AAC5C,MAAI,UAAU;GACZ,MAAM,mBAAmB,MAAM,KAAK,SAAS,CAAC,MAC3C,SAAS,KAAK,gBAAgB,OAAO,KACvC;AACD,OAAI,iBACF,QAAO;QACF;IACL,MAAMA,cAA4B;KAChC,aAAa,OAAO;KACpB,UAAU;KACV,UAAU;KACX;AACD,aAAS,IAAI,YAAY;AACzB,WAAO;;;;AAIb,OAAM,IAAI,MAAM,uCAAuC;;;;;AC5CzD,MAAaE,sBAAsBC,OAAO,wBAAA;AAO1C,SAAgBC,oBACdC,QACAC,SAA8B;AAE9B,KAAIA,QAAQC,UAAU;EACpB,MAAMA,WAAWD,QAAQC,SAASL;AAGlC,MAAIK,SACF,QAAOA;OACF;GACL,MAAMC,eAAeP,mBAAmBK,QAAAA;GACxC,MAAMG,cAAgC;IACpCC,MAAML,OAAOK;IACbC,MAAMH;IACR;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B,MAAMuB,MAAAA;;;IAGnDC,OAAO,CAAqBV,IAAIW;IAClC,CAAA;AACA,QAAKvB,KAAKwB,IAAI1B,MAAMmB,QAAAA;;;;;;;;;;;;;;;;;;;IAqBxBQ,WAAW;AACT,OAAK,MAAMb,OAAO,KAAKZ,KAAK0B,QAAM,EAAI;AACpC,OAAId,IAAIe,SACN;AAEFf,OAAIU,OAAK;;;;;;;;;;;;;;;;;;;;IAsBbM,UAAU;AACR,OAAK,MAAMhB,OAAO,KAAKZ,KAAK0B,QAAM,EAAI;AACpC,OAAI,CAACd,IAAIe,SACP;AAEFf,OAAIiB,MAAI"}
|
package/lib/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["newMetadata: CronMetadata","getAllCronMetadata","ScheduleMetadataKey","Symbol","getScheduleMetadata","target","context","metadata","jobsMetadata","newMetadata","name","jobs","Error","extractScheduleMetadata","hasScheduleMetadata","getCronMetadata","Cron","cronTime","options","target","context","kind","Error","metadata","disabled","globalRegistry","Injectable","getScheduleMetadata","Schedulable","registry","target","context","kind","Error","metadata","Schedule","Container","inject","Injectable","Logger","CronJob","extractScheduleMetadata","hasScheduleMetadata","SchedulerService","logger","context","name","container","jobs","Map","register","service","Error","metadata","debug","registerJobs","getJob","method","jobName","get","job","cronTime","classMethod","self","defaultDisabled","cronJob","from","onTick","instance","error","start","disabled","set","startAll","values","isActive","stopAll","stop"],"sources":["../src/metadata/cron.metadata.mts","../src/metadata/schedule.metadata.mts","../src/decorators/cron.decorator.mts","../src/decorators/schedulable.decorator.mts","../src/cron.constants.mts","../src/scheduler.service.mts"],"sourcesContent":["import type { CronJobParams } from 'cron'\n\nexport const CronMetadataKey = Symbol('CronMetadataKey')\n\nexport interface CronMetadata {\n classMethod: string\n cronTime: CronJobParams['cronTime'] | null\n disabled: boolean\n}\n\nexport function getAllCronMetadata(\n context: ClassMethodDecoratorContext | ClassDecoratorContext,\n): Set<CronMetadata> {\n if (context.metadata) {\n const metadata = context.metadata[CronMetadataKey] as\n | Set<CronMetadata>\n | undefined\n if (metadata) {\n return metadata\n } else {\n context.metadata[CronMetadataKey] = new Set<CronMetadata>()\n return context.metadata[CronMetadataKey] as Set<CronMetadata>\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n\nexport function getCronMetadata(\n target: Function,\n context: ClassMethodDecoratorContext,\n): CronMetadata {\n if (context.metadata) {\n const metadata = getAllCronMetadata(context)\n if (metadata) {\n const endpointMetadata = Array.from(metadata).find(\n (item) => item.classMethod === target.name,\n )\n if (endpointMetadata) {\n return endpointMetadata\n } else {\n const newMetadata: CronMetadata = {\n classMethod: target.name,\n cronTime: null,\n disabled: false,\n }\n metadata.add(newMetadata)\n return newMetadata\n }\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n","import type { ClassType } from '@navios/core'\n\nimport type { CronMetadata } from './cron.metadata.mjs'\n\nimport { getAllCronMetadata } from './cron.metadata.mjs'\n\nexport const ScheduleMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ScheduleMetadata {\n name: string\n jobs: Set<CronMetadata>\n}\n\nexport function getScheduleMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): ScheduleMetadata {\n if (context.metadata) {\n const metadata = context.metadata[ScheduleMetadataKey] as\n | ScheduleMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const jobsMetadata = getAllCronMetadata(context)\n const newMetadata: ScheduleMetadata = {\n name: target.name,\n jobs: jobsMetadata,\n }\n context.metadata[ScheduleMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[ScheduleMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n\nexport function extractScheduleMetadata(target: ClassType): ScheduleMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ScheduleMetadataKey] as ScheduleMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios-Schedule] Controller metadata not found. Make sure to use @Controller decorator.',\n )\n }\n return metadata\n}\n\nexport function hasScheduleMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ScheduleMetadataKey] as ScheduleMetadata | undefined\n\n return !!metadata\n}\n","import type { CronJobParams } from 'cron'\n\nimport { getCronMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a cron job.\n * \n * @public\n */\nexport interface CronOptions {\n /**\n * Whether the job should be disabled by default.\n * Disabled jobs won't start automatically but can be manually started later.\n * \n * @default false\n */\n disabled?: boolean\n}\n\n/**\n * Decorator that marks a method to run on a cron schedule.\n * \n * The method must be in a class decorated with `@Schedulable()`.\n * The method will be automatically executed according to the provided cron expression.\n * \n * @param cronTime - Cron expression (5 or 6 fields) or a pre-defined Schedule constant\n * @param options - Optional configuration for the cron job\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * // Run daily at midnight\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * console.log('Running daily task')\n * }\n * \n * // Use pre-defined schedule\n * @Cron(Schedule.EveryFiveMinutes)\n * async frequentTask() {\n * console.log('Running every 5 minutes')\n * }\n * \n * // Disabled job (won't start automatically)\n * @Cron('0 2 * * *', { disabled: true })\n * async maintenanceTask() {\n * console.log('Maintenance task')\n * }\n * }\n * ```\n * \n * @throws {Error} If applied to something other than a method\n * \n * @public\n */\nexport function Cron(\n cronTime: CronJobParams['cronTime'],\n options?: CronOptions,\n) {\n return (\n target: () => Promise<void>,\n context: ClassMethodDecoratorContext,\n ) => {\n if (context.kind !== 'method') {\n throw new Error(\n `Cron can only be applied to methods, not ${context.kind}`,\n )\n }\n if (context.metadata) {\n const metadata = getCronMetadata(target, context)\n metadata.cronTime = cronTime\n metadata.disabled = options?.disabled ?? false\n }\n return target\n }\n}\n","import type { ClassType } from '@navios/core'\n\nimport { globalRegistry, Injectable, Registry } from '@navios/core'\n\nimport { getScheduleMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that marks a class as schedulable and makes it injectable.\n *\n * Classes decorated with `@Schedulable()` can contain methods decorated with `@Cron()`\n * that will be automatically scheduled and executed. This decorator also applies\n * the `@Injectable()` decorator, making the class available for dependency injection.\n *\n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * // This will run daily at midnight\n * }\n * }\n *\n * // Register the service\n * schedulerService.register(TaskService)\n * ```\n *\n * @throws {Error} If applied to something other than a class\n *\n * @public\n */\nexport function Schedulable({ registry }: { registry?: Registry } = {}) {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error(\n `SchedulableDecorator can only be applied to classes, not ${context.kind}`,\n )\n }\n if (context.metadata) {\n getScheduleMetadata(target, context)\n }\n return Injectable({ registry: registry ?? globalRegistry })(target, context)\n }\n}\n","/**\n * Pre-defined cron schedule constants for common scheduling patterns.\n *\n * These constants provide convenient shortcuts for frequently used cron expressions,\n * making it easier to schedule jobs without manually writing cron expressions.\n *\n * @example\n * ```typescript\n * import { Schedule } from '@navios/schedule'\n *\n * @Schedulable()\n * class TaskService {\n * @Cron(Schedule.EveryMinute)\n * async everyMinute() {}\n *\n * @Cron(Schedule.EveryHour)\n * async hourly() {}\n *\n * @Cron(Schedule.EveryDay)\n * async daily() {}\n * }\n * ```\n *\n * @public\n */\nexport enum Schedule {\n EveryMinute = '*/1 * * * *',\n EveryFiveMinutes = '*/5 * * * *',\n EveryTenMinutes = '*/10 * * * *',\n EveryFifteenMinutes = '*/15 * * * *',\n EveryThirtyMinutes = '*/30 * * * *',\n EveryHour = '0 * * * *',\n EveryTwoHours = '0 */2 * * *',\n EveryThreeHours = '0 */3 * * *',\n EveryFourHours = '0 */4 * * *',\n EverySixHours = '0 */6 * * *',\n EveryTwelveHours = '0 */12 * * *',\n EveryDay = '0 0 * * *',\n EveryWeek = '0 0 * * 0',\n EveryMonth = '0 0 1 * *',\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Container, inject, Injectable, Logger } from '@navios/core'\n\nimport { CronJob } from 'cron'\n\nimport type { ScheduleMetadata } from './metadata/index.mjs'\n\nimport {\n extractScheduleMetadata,\n hasScheduleMetadata,\n} from './metadata/index.mjs'\n\n/**\n * Service responsible for managing and executing scheduled cron jobs.\n * \n * The SchedulerService registers schedulable services decorated with `@Schedulable()`\n * and automatically starts their cron jobs based on the `@Cron()` decorator configuration.\n * \n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/core'\n * import { SchedulerService } from '@navios/schedule'\n * \n * @Injectable()\n * class AppModule {\n * private readonly scheduler = inject(SchedulerService)\n * \n * async onModuleInit() {\n * this.scheduler.register(MySchedulableService)\n * }\n * }\n * ```\n * \n * @public\n */\n@Injectable()\nexport class SchedulerService {\n private readonly logger = inject(Logger, {\n context: SchedulerService.name,\n })\n private readonly container = inject(Container)\n private readonly jobs: Map<string, CronJob> = new Map()\n\n /**\n * Registers a schedulable service and starts all its cron jobs.\n * \n * The service must be decorated with `@Schedulable()` and contain methods\n * decorated with `@Cron()` to be registered successfully.\n * \n * @param service - The schedulable service class to register\n * @throws {Error} If the service is not decorated with `@Schedulable()`\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * // Runs daily at midnight\n * }\n * }\n * \n * schedulerService.register(TaskService)\n * ```\n * \n * @public\n */\n register(service: ClassType) {\n if (!hasScheduleMetadata(service)) {\n throw new Error(\n `[Navios-Schedule] Service ${service.name} is not schedulable. Make sure to use @Schedulable decorator.`,\n )\n }\n const metadata = extractScheduleMetadata(service)\n this.logger.debug('Scheduling service', metadata.name)\n this.registerJobs(service, metadata)\n }\n\n /**\n * Retrieves a specific cron job instance for a method in a schedulable service.\n * \n * @param service - The schedulable service class\n * @param method - The name of the method decorated with `@Cron()`\n * @returns The CronJob instance if found, undefined otherwise\n * \n * @example\n * ```typescript\n * const job = schedulerService.getJob(TaskService, 'dailyTask')\n * if (job) {\n * console.log('Job is active:', job.isActive)\n * job.start() // Manually start the job\n * job.stop() // Manually stop the job\n * }\n * ```\n * \n * @public\n */\n getJob<T extends ClassType>(\n service: T,\n method: keyof InstanceType<T>,\n ): CronJob | undefined {\n const metadata = extractScheduleMetadata(service)\n const jobName = `${metadata.name}.${method as string}()`\n return this.jobs.get(jobName)\n }\n\n private registerJobs(service: ClassType, metadata: ScheduleMetadata) {\n const jobs = metadata.jobs\n for (const job of jobs) {\n if (!job.cronTime) {\n this.logger.debug('Skipping job', job.classMethod)\n continue\n }\n const name = `${metadata.name}.${job.classMethod}()`\n const self = this\n const defaultDisabled = false\n const cronJob = CronJob.from({\n cronTime: job.cronTime,\n name,\n async onTick() {\n try {\n self.logger.debug('Executing job', name)\n const instance = await self.container.get(service)\n await instance[job.classMethod]()\n } catch (error) {\n self.logger.error('Error executing job', name, error)\n }\n },\n start: !(defaultDisabled || job.disabled),\n })\n this.jobs.set(name, cronJob)\n }\n }\n\n /**\n * Starts all registered cron jobs that are currently inactive.\n * \n * Only jobs that are not already active will be started. This method\n * is useful for resuming all jobs after calling `stopAll()`.\n * \n * @example\n * ```typescript\n * // Stop all jobs\n * schedulerService.stopAll()\n * \n * // Later, resume all jobs\n * schedulerService.startAll()\n * ```\n * \n * @public\n */\n startAll() {\n for (const job of this.jobs.values()) {\n if (job.isActive) {\n continue\n }\n job.start()\n }\n }\n\n /**\n * Stops all registered cron jobs that are currently active.\n * \n * Only jobs that are currently active will be stopped. This method\n * is useful for pausing all scheduled tasks, for example during\n * application shutdown or maintenance.\n * \n * @example\n * ```typescript\n * // Pause all scheduled jobs\n * schedulerService.stopAll()\n * \n * // Jobs can be resumed later with startAll()\n * schedulerService.startAll()\n * ```\n * \n * @public\n */\n stopAll() {\n for (const job of this.jobs.values()) {\n if (!job.isActive) {\n continue\n }\n job.stop()\n }\n }\n}\n"],"mappings":";;;;AAEA,MAAa,kBAAkB,OAAO,kBAAkB;AAQxD,SAAgB,mBACd,SACmB;AACnB,KAAI,QAAQ,UAAU;EACpB,MAA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