Skip to content

Commit

Permalink
fix: schedule handler
Browse files Browse the repository at this point in the history
  • Loading branch information
SIY1121 committed Mar 23, 2021
1 parent 8c834e1 commit 0020c6f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 deletions.
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { connectDatabase } from './database'
import { startGrpcServer } from './grpc'
import { logger } from './logger'
import { scheduleTotalAmountUpdate } from './usecase/getTotalAmount'
import { scheduleListContributorsUpdate } from './usecase/listContributors'

async function main() {
logger.info('starting...')
await connectDatabase()
await startGrpcServer()
scheduleListContributorsUpdate()
scheduleTotalAmountUpdate()
}

main()
15 changes: 9 additions & 6 deletions src/usecase/getTotalAmount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export async function getTotalAmountUseCase(
mandatory: boolean
): Promise<number> {
if ((mandatory || !cachedTotalAmount) && !pending) await updateData()
else if (pending) await pending
return cachedTotalAmount!
}

Expand Down Expand Up @@ -40,8 +39,12 @@ function delay(ms: number) {
})
}

schedule.scheduleJob('*/15,45 * * * *', async () => {
pending = updateData()
await pending
pending = undefined
})
export let updateTotalAmountJob: schedule.Job | undefined

export function scheduleTotalAmountUpdate() {
updateTotalAmountJob = schedule.scheduleJob('*/15,45 * * * *', async () => {
pending = updateData()
await pending
pending = undefined
})
}
16 changes: 14 additions & 2 deletions src/usecase/listContributors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { logger, logger as schedulerLogger } from '../logger'
import schedule from 'node-schedule'

let cachedUsers: PaymentUser[] | undefined
let pending: Promise<void> | undefined

/**
* 寄付してくれたユーザー一覧を取得
Expand All @@ -15,7 +16,7 @@ let cachedUsers: PaymentUser[] | undefined
export async function listContributorUseCase(
mandatory: boolean
): Promise<PaymentUser[]> {
if (mandatory || !cachedUsers) await updateData()
if ((mandatory || !cachedUsers) && !pending) await updateData()
return cachedUsers!
}

Expand All @@ -35,4 +36,15 @@ async function updateData() {
logger.info('寄付者一覧の更新完了')
}

schedule.scheduleJob('*/0,30 * * * *', () => updateData())
export let updateListContributorsJob: schedule.Job | undefined

export function scheduleListContributorsUpdate() {
updateListContributorsJob = schedule.scheduleJob(
'*/0,30 * * * *',
async () => {
pending = updateData()
await pending
pending = undefined
}
)
}

0 comments on commit 0020c6f

Please sign in to comment.