Created
December 8, 2024 15:12
-
-
Save johnlindquist/724e9573e53c88eec5f551c8157915d7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 "@johnlindquist/kit" | |
import schedule from "node-schedule" | |
export const metadata: Metadata = { | |
name: "Testing Node Schedule", | |
background: "auto", | |
} | |
type ScheduleState = { | |
name: string | |
pattern: string | |
nextState: string | null | |
validateTransition?: () => boolean | |
} | |
const states: Record<string, ScheduleState> = { | |
everySecond: { | |
name: "Every Second", | |
pattern: "* * * * * *", | |
nextState: "everyMinute", | |
}, | |
everyMinute: { | |
name: "Every Minute", | |
pattern: "* * * * *", | |
nextState: "everyHour", | |
validateTransition: () => currentJob?.nextInvocation().getSeconds() === 0, | |
}, | |
everyHour: { | |
name: "Every Hour", | |
pattern: "0 * * * *", | |
nextState: null, | |
validateTransition: () => currentJob?.nextInvocation().getMinutes() === 0, | |
}, | |
} | |
let currentJob: schedule.Job | null = null | |
let currentState = "everySecond" | |
let executionCount = 0 | |
const cancelCurrentJob = () => { | |
if (currentJob) { | |
currentJob.cancel() | |
currentJob = null | |
} | |
} | |
const transitionToState = (stateName: string) => { | |
const state = states[stateName] | |
console.log(`\nSwitching to ${state.name.toLowerCase()} schedule...`) | |
cancelCurrentJob() | |
currentJob = schedule.scheduleJob(state.pattern, logTime) | |
currentState = stateName | |
executionCount = 0 | |
} | |
const logTime = () => { | |
executionCount++ | |
console.log(`Current time: ${new Date().toLocaleTimeString()}`) | |
const state = states[currentState] | |
if (executionCount === 5) { | |
const { nextState, validateTransition } = state | |
if (!nextState) { | |
console.log("\nStopping all schedules...") | |
cancelCurrentJob() | |
return | |
} | |
if (!validateTransition || validateTransition()) { | |
transitionToState(nextState) | |
} | |
} | |
} | |
// Start with every second | |
transitionToState("everySecond") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment