我有一个带有任务的 MongoDB 集合。每个任务都有一个以秒为单位的间隔、任务标识符和应通过 HTTP POST 发送的有效负载,以收集结果并将它们存储到另一个集合中。
可能有数千个具有不同间隔的任务,我不知道如何安排它们。
目前我正在使用每 10 毫秒按上次执行时间进行的简单轮询,但它会对数据库产生沉重的负载。
看起来像这样
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 - 从数据库按时间间隔调度任务的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32400699/