background-job 2.0.0 → 2.0.1

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 CHANGED
@@ -1,9 +1,10 @@
1
1
  # Background Job
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/background-job.svg)](https://www.npmjs.com/package/background-job)
4
+ [![license](https://img.shields.io/github/license/mahelbir/background-job.svg)](https://github.com/mahelbir/background-job/blob/HEAD/LICENSE)
4
5
 
5
- Managed background jobs for Node.js. Provides suspension, disabling, and controlled execution loops for long-running
6
- worker processes.
6
+ Managed background jobs with controlled execution loops and per-job enabling, disabling, suspension, and cooldown for
7
+ long-running workers.
7
8
 
8
9
  ## Installation
9
10
 
@@ -11,7 +12,7 @@ worker processes.
11
12
  npm i background-job
12
13
  ```
13
14
 
14
- Ships a dual ESM/CJS build, so both forms are supported:
15
+ The package ships both ESM and CommonJS builds:
15
16
 
16
17
  ```javascript
17
18
  // ES Module
@@ -27,7 +28,8 @@ Subclass `BackgroundJob` for the work and `BackgroundJobRunner` to enumerate whi
27
28
 
28
29
  ### Fixed worker pool
29
30
 
30
- A set of identical workers that each loop with a delay — sized from config, backing off when there is nothing to do:
31
+ Identical workers that each loop with a delay. Config sets the pool size, and a worker backs off when there is nothing
32
+ to do:
31
33
 
32
34
  ```javascript
33
35
  import {BackgroundJob, BackgroundJobRunner} from "background-job";
@@ -54,7 +56,7 @@ await new QueueRunner("queue").executeJobs(); // runs forever, polling for execu
54
56
 
55
57
  ### One job per entity
56
58
 
57
- When the work is dynamic — one job per row from a data source — return the `BackgroundJobDefinition` objects directly.
59
+ When the work is dynamic, such as one job per row from a data source, return `BackgroundJobDefinition` objects directly.
58
60
  `initParams` carries per-job context into `init()`, and the lifecycle hooks set up and tear down resources:
59
61
 
60
62
  ```javascript
@@ -90,8 +92,8 @@ class AccountRunner extends BackgroundJobRunner {
90
92
  await new AccountRunner("account").executeJobs();
91
93
  ```
92
94
 
93
- Returning a job's id keeps it running; omitting it on a later poll disables it (and triggers its `destroy()`).
94
- `getExecutableJobs()` is the single source of truth for what should be active.
95
+ `getExecutableJobs()` decides which jobs are active on every poll. A returned id keeps its job running. If a later poll
96
+ leaves the id out, the runner disables the job and calls its `destroy()` once the loop ends.
95
97
 
96
98
  ## How it works
97
99
 
@@ -103,14 +105,14 @@ thundering herd, then loops its own `execute()` with the configured delay until
103
105
 
104
106
  ### `BackgroundJob`
105
107
 
106
- Base class for an individual job. The runner instantiates it for you — subclass and override the hooks.
108
+ Base class for an individual job. You subclass it and override the hooks; the runner creates the instances.
107
109
 
108
110
  | Member | Description |
109
111
  |-------------------------------------|-------------------------------------------------------------------------------------------------|
110
112
  | `async execute()` | **Abstract.** The job's work; must be overridden or it throws. Called repeatedly while enabled. |
111
113
  | `init(params)` | Optional setup hook, called once before the loop starts. |
112
114
  | `destroy()` | Optional teardown hook, called once after the loop ends. |
113
- | `isEnabled()` | `boolean` — whether this job is still enabled in the runner. |
115
+ | `isEnabled()` | Returns whether this job is still enabled in the runner. |
114
116
  | `disable(suspendDurationMs = 5000)` | Disables the job and suspends it for a cooldown; pass `0` to disable without suspending. |
115
117
  | `runner` / `id` / `name` | The owning runner, this job's id, and its derived name (`"<base> #<id>"`). |
116
118
 
@@ -130,16 +132,17 @@ Orchestrator that owns enabled/running/suspended state per job id.
130
132
 
131
133
  ### `BackgroundJobDefinition`
132
134
 
133
- The object returned (per job) by `getExecutableJobs()`:
135
+ `getExecutableJobs()` returns one of these per job:
134
136
 
135
137
  | Field | Type | Description |
136
138
  |----------------|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
137
139
  | `id` | `string \| number` | Unique job identifier. |
138
140
  | `jobClass` | `typeof BackgroundJob` | The `BackgroundJob` subclass to instantiate. |
139
- | `initParams` | `*` | Optional — passed to the job's `init()`. |
140
- | `delayMs` | `number` | Optional (default `0`) — delay between executions in ms. |
141
- | `isFixedDelay` | `boolean` | Optional (default `true`) — when `true`, the full delay is waited after each execute (fixed-delay); when `false`, execute time counts toward the delay (fixed-rate). |
141
+ | `initParams` | `*` | Optional. Passed to the job's `init()`. |
142
+ | `delayMs` | `number` | Optional, default `0`. Delay between executions in ms. |
143
+ | `isFixedDelay` | `boolean` | Optional, default `true`. When `true`, the job waits the full delay after each run (fixed-delay); when `false`, execute time counts toward the delay (fixed-rate). |
142
144
 
143
- ## License
145
+ ## Support
144
146
 
145
- The MIT License (MIT). Please see [License File](LICENSE) for more information.
147
+ If this project helps you, please consider giving it a [Star ⭐️](https://github.com/mahelbir/background-job) on GitHub.
148
+ This will encourage us to continue developing and maintaining this project.
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let melperjs = require("melperjs");
3
- //#region src/utils.js
3
+ // src/utils.js
4
4
  /**
5
5
  * Throws to signal an abstract method that a subclass must override.
6
6
  * @param {string} method - Name of the method that must be implemented
@@ -15,8 +15,7 @@ var BackgroundJobDefinitionError = class extends Error {
15
15
  this.name = "BackgroundJobDefinitionError";
16
16
  }
17
17
  };
18
- //#endregion
19
- //#region src/background-job.js
18
+ // src/background-job.js
20
19
  /**
21
20
  * Base class for an individual background job.
22
21
  * Subclass and override {@link BackgroundJob#execute} for the work, with
@@ -69,8 +68,7 @@ var BackgroundJob = class {
69
68
  suspendDurationMs && this.runner.suspendJob(this.id, suspendDurationMs);
70
69
  }
71
70
  };
72
- //#endregion
73
- //#region src/background-job-runner.js
71
+ // src/background-job-runner.js
74
72
  /**
75
73
  * @typedef {Object} BackgroundJobDefinition
76
74
  * @property {string|number} id - Unique job identifier
@@ -151,10 +149,12 @@ var BackgroundJobRunner = class {
151
149
  } catch (e) {
152
150
  console.error(`[${ref.name}] error`, e);
153
151
  }
154
- if (definition.delayMs > 0) if (definition.isFixedDelay) await (0, melperjs.sleepMs)(definition.delayMs);
155
- else {
156
- const remaining = definition.delayMs - (Date.now() - startTime);
157
- if (remaining > 0) await (0, melperjs.sleepMs)(remaining);
152
+ if (definition.delayMs > 0) {
153
+ if (definition.isFixedDelay) await (0, melperjs.sleep)(definition.delayMs);
154
+ else {
155
+ const remaining = definition.delayMs - (Date.now() - startTime);
156
+ if (remaining > 0) await (0, melperjs.sleep)(remaining);
157
+ }
158
158
  }
159
159
  }
160
160
  ref.destroy();
@@ -185,7 +185,7 @@ var BackgroundJobRunner = class {
185
185
  * @returns {Promise<void>}
186
186
  */
187
187
  async executeJobs(pollIntervalMs = 1e3) {
188
- await (0, melperjs.forever)(pollIntervalMs, async () => {
188
+ await (0, melperjs.forever)(async () => {
189
189
  const jobs = await this.getExecutableJobs();
190
190
  this._validateJobs(jobs);
191
191
  this.enabledJobs = {};
@@ -198,14 +198,14 @@ var BackgroundJobRunner = class {
198
198
  }
199
199
  } else this.enabledJobs[id] = true;
200
200
  if (this.isJobEnabled(id) && !this.isJobRunning(id)) {
201
- await (0, melperjs.sleepMs)((0, melperjs.randomInteger)(300, 1e3));
201
+ await (0, melperjs.sleep)((0, melperjs.randomInteger)(300, 1e3));
202
202
  this._startJob(job).catch(console.error);
203
203
  }
204
204
  }
205
- }, (e) => {
205
+ }, pollIntervalMs, { onError: (e) => {
206
206
  if (e instanceof BackgroundJobDefinitionError) throw e;
207
207
  console.error(`[${this.name}] error`, e);
208
- });
208
+ } });
209
209
  }
210
210
  /**
211
211
  * @abstract Override in a subclass to enumerate executable jobs.
@@ -231,7 +231,6 @@ var BackgroundJobRunner = class {
231
231
  }));
232
232
  }
233
233
  };
234
- //#endregion
235
234
  exports.BackgroundJob = BackgroundJob;
236
235
  exports.BackgroundJobDefinitionError = BackgroundJobDefinitionError;
237
236
  exports.BackgroundJobRunner = BackgroundJobRunner;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { forever, randomInteger, sleepMs } from "melperjs";
2
- //#region src/utils.js
1
+ import { forever, randomInteger, sleep } from "melperjs";
2
+ // src/utils.js
3
3
  /**
4
4
  * Throws to signal an abstract method that a subclass must override.
5
5
  * @param {string} method - Name of the method that must be implemented
@@ -14,8 +14,7 @@ var BackgroundJobDefinitionError = class extends Error {
14
14
  this.name = "BackgroundJobDefinitionError";
15
15
  }
16
16
  };
17
- //#endregion
18
- //#region src/background-job.js
17
+ // src/background-job.js
19
18
  /**
20
19
  * Base class for an individual background job.
21
20
  * Subclass and override {@link BackgroundJob#execute} for the work, with
@@ -68,8 +67,7 @@ var BackgroundJob = class {
68
67
  suspendDurationMs && this.runner.suspendJob(this.id, suspendDurationMs);
69
68
  }
70
69
  };
71
- //#endregion
72
- //#region src/background-job-runner.js
70
+ // src/background-job-runner.js
73
71
  /**
74
72
  * @typedef {Object} BackgroundJobDefinition
75
73
  * @property {string|number} id - Unique job identifier
@@ -150,10 +148,12 @@ var BackgroundJobRunner = class {
150
148
  } catch (e) {
151
149
  console.error(`[${ref.name}] error`, e);
152
150
  }
153
- if (definition.delayMs > 0) if (definition.isFixedDelay) await sleepMs(definition.delayMs);
154
- else {
155
- const remaining = definition.delayMs - (Date.now() - startTime);
156
- if (remaining > 0) await sleepMs(remaining);
151
+ if (definition.delayMs > 0) {
152
+ if (definition.isFixedDelay) await sleep(definition.delayMs);
153
+ else {
154
+ const remaining = definition.delayMs - (Date.now() - startTime);
155
+ if (remaining > 0) await sleep(remaining);
156
+ }
157
157
  }
158
158
  }
159
159
  ref.destroy();
@@ -184,7 +184,7 @@ var BackgroundJobRunner = class {
184
184
  * @returns {Promise<void>}
185
185
  */
186
186
  async executeJobs(pollIntervalMs = 1e3) {
187
- await forever(pollIntervalMs, async () => {
187
+ await forever(async () => {
188
188
  const jobs = await this.getExecutableJobs();
189
189
  this._validateJobs(jobs);
190
190
  this.enabledJobs = {};
@@ -197,14 +197,14 @@ var BackgroundJobRunner = class {
197
197
  }
198
198
  } else this.enabledJobs[id] = true;
199
199
  if (this.isJobEnabled(id) && !this.isJobRunning(id)) {
200
- await sleepMs(randomInteger(300, 1e3));
200
+ await sleep(randomInteger(300, 1e3));
201
201
  this._startJob(job).catch(console.error);
202
202
  }
203
203
  }
204
- }, (e) => {
204
+ }, pollIntervalMs, { onError: (e) => {
205
205
  if (e instanceof BackgroundJobDefinitionError) throw e;
206
206
  console.error(`[${this.name}] error`, e);
207
- });
207
+ } });
208
208
  }
209
209
  /**
210
210
  * @abstract Override in a subclass to enumerate executable jobs.
@@ -230,5 +230,4 @@ var BackgroundJobRunner = class {
230
230
  }));
231
231
  }
232
232
  };
233
- //#endregion
234
233
  export { BackgroundJob, BackgroundJobDefinitionError, BackgroundJobRunner };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "background-job",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "private": false,
5
- "description": "Managed background jobs for Node.js — suspension, disabling, and controlled execution loops.",
5
+ "description": "Managed background jobs with controlled execution loops and per-job enabling, disabling, suspension, and cooldown for long-running workers.",
6
6
  "keywords": [
7
7
  "worker",
8
8
  "runner",
@@ -19,6 +19,7 @@
19
19
  "license": "MIT",
20
20
  "author": "Mahmuthan Elbir <me@mahmuthanelbir.com.tr>",
21
21
  "type": "module",
22
+ "sideEffects": false,
22
23
  "exports": {
23
24
  ".": {
24
25
  "import": "./dist/index.mjs",
@@ -36,10 +37,10 @@
36
37
  "relock": "rm -rf node_modules package-lock.json && NODE_ENV= npm install --include=dev --include=optional"
37
38
  },
38
39
  "dependencies": {
39
- "melperjs": "^17.2.0"
40
+ "melperjs": "^18.1.0"
40
41
  },
41
42
  "devDependencies": {
42
- "tsdown": "^0.22.3"
43
+ "tsdown": "^0.23.8"
43
44
  },
44
45
  "engines": {
45
46
  "node": ">=18.0.0"