我有多个访问同一mongodb的node.js实例,它们都在执行相同的任务。我想确保在保存时间没有运行相同的任务。是否有“最佳实践”方法来签出任务?
到目前为止,这是我所拥有的,但这不是最好的方法,因为我似乎仍在发送重复的消息。
我在做什么错?我该怎么做呢?
// Check if there is a locked message.
const cutoff = moment()
.subtract(3, "minute")
.toDate();
let message = await Message.findOneAndUpdate(
{
listingID: listing._id,
messageRuleID: messageRule._id,
reservationID: reservation._id,
disable: {$ne: true}, // Message is not disabled
messageSent: {$ne: true}, // Message is not sent
$or: [
{
lockedAt: null // If the message is not locked (null)
},
{
lockedAt: {$exists: false} // If the message is not locked (doesn't exist)
},
{
lockedAt: {$lte: cutoff} // If it was locked more that 3 minutes ago
}
]
},
{
listingID: listing._id,
messageRuleID: messageRule._id,
reservationID: reservation._id,
lockedAt: moment().toDate() // Check out the message with the current date
},
{upsert: true, new: true}
);
// If no message doc is returned, that means it's disabled, has already been sent or is being sent.
if (!message) {
return;
}