這可以通過設置一個CloudWatch的事件規則觸發您的lambda表達式來完成。在每次調用Lambda函數時,該函數都需要確定其下一次運行時間並適當修改事件規則。
var AWS = require("aws-sdk");
exports.handler = function(event, context) {
var cloudwatchevents = new AWS.CloudWatchEvents();
var intervals = Array(3, 5, 7);
var nextInterval = intervals[Math.floor(Math.random()*intervals.length)];
var currentTime = new Date().getTime(); // UTC Time
var nextTime = dateAdd(currentTime, "minute", nextInterval);
var nextMinutes = nextTime.getMinutes();
var nextHours = nextTime.getHours();
// =================================
// DO YOUR WORK HERE
// =================================
var scheduleExpression = "cron(" + nextMinutes + " " + nextHours + " * * ? *)";
var params = {
Name: "YOUR CLOUDWATCH EVENT RULE NAME",
ScheduleExpression: scheduleExpression
};
cloudwatchevents.putRule(params, function(err, data) {
if (err) {
console.log(err, err.stack);
}
else {
console.log(data);
}
})
};
var dateAdd = function(date, interval, units) {
var ret = new Date(date); // don't change original date
switch(interval.toLowerCase()) {
case 'year' : ret.setFullYear(ret.getFullYear() + units); break;
case 'quarter': ret.setMonth(ret.getMonth() + 3*units); break;
case 'month' : ret.setMonth(ret.getMonth() + units); break;
case 'week' : ret.setDate(ret.getDate() + 7*units); break;
case 'day' : ret.setDate(ret.getDate() + units); break;
case 'hour' : ret.setTime(ret.getTime() + units*3600000); break;
case 'minute' : ret.setTime(ret.getTime() + units*60000); break;
case 'second' : ret.setTime(ret.getTime() + units*1000); break;
default : ret = undefined; break;
}
return ret;
}
你應該能夠交換我的抽籤用自己的調度邏輯和插入你在的地方我的評論的需要的任何工作。
您需要替換您的活動規則的名字在我的片段:「你CloudWatch的事件規則名稱」。
一個博客大問題:AWS Lambda Functions That Dynamically Schedule Their Next Runtime
我沒有看過這個的任何細節,但你只需一些代碼添加到您的lambda函數編輯這實際上觸發拉姆達的CloudWatch的活動日程?相關:http://stackoverflow.com/questions/27382009/aws-lambda-scheduled-tasks?rq=1 – jarmod