Last active
June 22, 2021 13:23
-
-
Save alirezabonab/1ee8b8accf1da21ab456290b97a700af to your computer and use it in GitHub Desktop.
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
import { Logger, OnModuleInit } from '@nestjs/common'; | |
import { SchedulerRegistry } from '@nestjs/schedule'; | |
type Fulfilled = 'fulfilled'; | |
type Rejected = 'rejected'; | |
export interface ResolvedItem<T> { | |
status: Fulfilled; | |
value: T; | |
} | |
export interface RejectedItem { | |
status: Rejected; | |
reason: Error; | |
} | |
export type SettledItem<T> = RejectedItem | ResolvedItem<T>; | |
export abstract class PollerService implements OnModuleInit { | |
protected logger: Logger; | |
private isRunning = false; | |
constructor( | |
private readonly schedulerRegistry: SchedulerRegistry, | |
public readonly timeout: number = 1000, | |
) { | |
this.logger = new Logger(this.constructor.name); | |
} | |
onModuleInit() { | |
const interval = setInterval(async () => { | |
if (this.isRunning) { | |
this.logger.log('poll() was running, skipping this interval'); | |
return; | |
} | |
try { | |
this.isRunning = true; | |
await this.poll(); | |
} catch (e) { | |
if (e instanceof Error) { | |
this.logger.error(e.message, e.stack); | |
} else { | |
this.logger.error(e.toString()); | |
} | |
} finally { | |
this.isRunning = false; | |
} | |
}, this.timeout); | |
// Add the interval to the registry, so that it is properly cleared when the application exits. | |
this.schedulerRegistry.addInterval( | |
`${this.constructor.name}_syncInterval`, | |
interval, | |
); | |
} | |
abstract async poll(): Promise<void>; | |
protected logRejections<T>(rejectedResults: SettledItem<T>[]) { | |
for (const result of rejectedResults) { | |
if (result.status === 'rejected') { | |
if (result.reason instanceof Error) { | |
this.logger.error(result.reason.message, result.reason.stack); | |
} else { | |
this.logger.error(result.reason); | |
} | |
} | |
} | |
} | |
} | |
// ****************** USAGE | |
@Injectable() | |
export class CatService extends PollerService { | |
constructor( | |
@Inject(SchedulerRegistry) | |
schedulerRegistry: SchedulerRegistry | |
){ | |
super(schedulerRegistry , 5000) | |
} | |
async poll() { | |
console.log('do your recurring job every 5 seconds!') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment