Skip to content

Commit

Permalink
Simplify first-run logic for JobRunner
Browse files Browse the repository at this point in the history
  • Loading branch information
justinyaodu committed Oct 3, 2023
1 parent 9a8ef5a commit 82c5593
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 46 deletions.
8 changes: 6 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,14 @@ async function main() {
}

const runner = await JobRunner.create(app);
runner.run().catch(console.error);
await runner.waitForFirstRun();
await runner.run();

shell(app).catch(console.error);

while (true) {
await runner.timer.wait();
await runner.run();
}
}

main().catch(console.error);
69 changes: 25 additions & 44 deletions src/jobs/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,11 @@ import { allJobs } from "./jobs";

class JobRunner {
private reloadPending = false;
private firstRun: Promise<void>;
private firstRunResolve: (() => void) | null = null;

private constructor(
private app: App,
private timer: IntervalTimer,
) {
this.firstRun = new Promise((resolve) => {
this.firstRunResolve = resolve;
});
}
public timer: IntervalTimer,
) {}

static async create(app: App): Promise<JobRunner> {
const timer = await JobRunner.getTimer(app);
Expand All @@ -42,48 +36,35 @@ class JobRunner {
return new IntervalTimer(intervalMs, startMs);
}

async run(): Promise<never> {
while (true) {
console.log(`running scheduled jobs: ${new Date().toISOString()}`);

for (const cls of allJobs) {
const job = new cls(this.app);
console.log(`running job: ${cls.description}`);

let result;
try {
result = await job.run();
} catch (e) {
console.error(e);
console.log("(err)");
continue;
}

if (result.ok) {
console.log(result.value);
console.log("(ok)");
} else {
console.log(result.error);
console.log("(err)");
}
}
async run(): Promise<void> {
console.log(`running scheduled jobs: ${new Date().toISOString()}`);

if (this.firstRunResolve !== null) {
this.firstRunResolve();
this.firstRunResolve = null;
}
for (const cls of allJobs) {
const job = new cls(this.app);
console.log(`running job: ${cls.description}`);

if (this.reloadPending) {
await this.reload();
this.reloadPending = false;
let result;
try {
result = await job.run();
} catch (e) {
console.error(e);
console.log("(err)");
continue;
}

await this.timer.wait();
if (result.ok) {
console.log(result.value);
console.log("(ok)");
} else {
console.log(result.error);
console.log("(err)");
}
}
}

async waitForFirstRun(): Promise<void> {
return this.firstRun;
if (this.reloadPending) {
await this.reload();
this.reloadPending = false;
}
}

onConfigCacheReload() {
Expand Down

0 comments on commit 82c5593

Please sign in to comment.