Skip to content

Commit

Permalink
Merge pull request #90 from oliver-oloughlin/feature/cron-on-exit
Browse files Browse the repository at this point in the history
added onExit option to cron jobs, renamed retries option to retry
  • Loading branch information
oliver-oloughlin authored Oct 8, 2023
2 parents 9b1a7a0 + 2007602 commit 4597cf1
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
6 changes: 4 additions & 2 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,7 @@ export const GET_MANY_KEY_LIMIT = 10

export const LARGE_COLLECTION_STRING_LIMIT = 25_000

// Time constants
export const DEFAULT_CRON_INTERVAL = 1_000
// Cron constants
export const DEFAULT_CRON_INTERVAL = 60 * 60 * 1_000 // 1 hour

export const DEFAULT_CRON_RETRY = 10
5 changes: 3 additions & 2 deletions src/kvdex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import { AtomicBuilder } from "./atomic_builder.ts"
import {
DEFAULT_CRON_INTERVAL,
DEFAULT_CRON_RETRY,
KVDEX_KEY_PREFIX,
UNDELIVERED_KEY_PREFIX,
} from "./constants.ts"
Expand Down Expand Up @@ -356,7 +357,7 @@ export class KvDex<const T extends Schema<SchemaDefinition>> {
delay: number | undefined,
) => {
// Enqueue cron job until delivered
for (let i = 0; i <= (options?.retries ?? 10); i++) {
for (let i = 0; i <= (options?.retry ?? DEFAULT_CRON_RETRY); i++) {
await this.enqueue(msg, {
idsIfUndelivered: [id],
delay,
Expand All @@ -379,8 +380,8 @@ export class KvDex<const T extends Schema<SchemaDefinition>> {
this.listenQueue<CronMessage>(async (msg) => {
// Check if exit criteria is met, end repeating cron job if true
const exit = await options?.exitOn?.(msg) ?? false

if (exit) {
await options?.onExit?.(msg)
return
}

Expand Down
7 changes: 5 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export type CronOptions = {
/**
* Interval in milliseconds for cron job.
*
* @default 1000 // Defaults to 1 second
* @default 3_600_000 // Defaults to 1 hour
*/
interval?: number

Expand All @@ -43,6 +43,9 @@ export type CronOptions = {
/** Exit predicate used to end cron job. */
exitOn?: (msg: CronMessage) => boolean | Promise<boolean>

/** Task to be run when terminating a cron job (after ```exitOn()``` returns true) */
onExit?: (msg: CronMessage) => unknown

/**
* Delay before running the first job.
*
Expand All @@ -57,7 +60,7 @@ export type CronOptions = {
*
* @default 10
*/
retries?: number
retry?: number
}

export type CronMessage = {
Expand Down

0 comments on commit 4597cf1

Please sign in to comment.