-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Wait on blockchain processing completion when polling (#156)
* wait on processing completion * increase polling frequency * log execution time less frequently * refactor to iterable polling, fix concurrency * start/stop scheduling in project lifecycle hooks
- Loading branch information
1 parent
be49856
commit 5f5d9c0
Showing
2 changed files
with
77 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { Logger } from "@nestjs/common"; | ||
|
||
const logger = new Logger("Utils"); | ||
|
||
export type ExecutableCallback = () => Promise<void>; | ||
|
||
export type AsyncIntervalOptions = { | ||
functionToExecute: ExecutableCallback; | ||
name: string; | ||
intervalInMs: number; | ||
}; | ||
|
||
/** | ||
* Runs the provided function in interval. | ||
* Waits for promise completion until rerunning interval. | ||
*/ | ||
export class AsyncIntervalScheduler { | ||
private isRunning: boolean; | ||
private runningTimeoutId: NodeJS.Timeout; | ||
private readonly options: AsyncIntervalOptions; | ||
|
||
constructor(options: AsyncIntervalOptions) { | ||
this.options = options; | ||
this.isRunning = false; | ||
} | ||
|
||
async start(): Promise<void> { | ||
if (this.isRunning) { | ||
return; | ||
} | ||
this.isRunning = true; | ||
await this.pollIfRunning(); | ||
} | ||
|
||
stop(): void { | ||
clearTimeout(this.runningTimeoutId); | ||
this.isRunning = false; | ||
} | ||
|
||
private async pollIfRunning() { | ||
const { intervalInMs } = this.options; | ||
while (this.isRunning) { | ||
await this.executeCallback(); | ||
await new Promise((resolve) => { | ||
this.runningTimeoutId = setTimeout(resolve, intervalInMs); | ||
}); | ||
} | ||
} | ||
|
||
private async executeCallback() { | ||
const { functionToExecute, name, intervalInMs } = this.options; | ||
try { | ||
const startTime = new Date(); | ||
await functionToExecute(); | ||
const endTime = new Date(); | ||
const runTimeInMs = endTime.getTime() - startTime.getTime(); | ||
if (runTimeInMs > intervalInMs) { | ||
logger.debug(`${name} took ${runTimeInMs}ms`); | ||
} | ||
} catch (e) { | ||
logger.error(`${name} failed`, e); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters