【发布时间】:2015-09-04 14:35:41
【问题描述】:
我有一个带有任务的 MongoDB 集合。每个任务都有一个以秒为单位的间隔、任务标识符和负载,应通过 HTTP POST 发送以收集结果并将它们存储到另一个集合中。
可能有数千个不同间隔的任务,我不知道如何安排它们。
目前我正在使用每 10 毫秒最后一次执行时间的简单轮询,但它会在 DB 上产生沉重的负载。
它看起来像这样
mongo.MongoClient.connect(MONGO_URL, (err, db) ->
handle_error(err)
schedule = (collection) ->
collection.find({isEnabled:true, '$where': '((new Date()).getTime() - this.timestamp) > (this.checkInterval * 60 * 1000)'}).toArray((err, docs) ->
handle_error(err)
for i, doc of docs
collection.update({_id: doc._id}, {'$set': {timestamp: (new Date()).getTime()}}, {w: 1})
task = prepare(doc)
request.post({url: url, formData: {task: JSON.stringify(prepare(doc))}}, (err,httpResponse,body) ->
result = JSON.parse(body)
console.log(result)
db.collection(MONGO_COLLECTION_RESULTS).save({
task: result.id,
type: result.type,
data: result
})
)
setTimeout((() -> schedule(collection)), 10)
)
setTimeout((() -> schedule(db.collection(MONGO_COLLECTION_TASKS))), 10)
)
任务可以添加、更新、删除,我必须处理它。 使用redis怎么样?但是当某些任务正在等待结果、间隔已更改等时,我不知道如何将数据从 mongo 同步到 redis
请为此建议最佳策略
【问题讨论】:
标签: mongodb asynchronous cron redis scheduling