简体   繁体   中英

Mongoose - execute a function on a specific date in the document

I'm working on a cryptocurrency related betting game project. I use mongodb as my database and mongoose to work with it. I have this collection for documents that describe betting games. Each document has a field called “expires” which is normally would be 3 minutes after it was created. No bets should be added after this date and a function should be ran to end the game: make all the relevant calculations to find a winner and set the game alive status to false. There can only be one alive game in the database and I achieve this using the partial index for the alive field. I need to create a mechanism that would end games on their expired date and I have no idea what's the best approach here.

So far I'm considering these solutions: * Run a separate node instance that performs checks on the alive game and its expiry date every 1-3 seconds. * Schedule execution of the function that's responsible for ending the game just after the expiry date gets introduced.

Are there any better approaches to solve this? Is my game design appropriate or have I went somewhere completely wrong implementing this functionality? Would storing the game object in memory and saving it once ended be a better design?

This is classic job scheduler problem , very common in banks where any transaction has to be completed within a time frame if, it doesn't get completed within that amount of time you end up the transaction to its last Atomic state of Database. I would suggest you to look at node-cron , this a scheduler which works on scheduling pattern which looks like these .

'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM