mongodb中cron定时任务
需求:
每天定时清除mongodb中某一天之前的数据
思路:
采用shell脚本调用mongodb的命令执行js脚本即可。
步骤:
1.编写email.js文件,作用:清除mongodb某天之前数据,具体代码如下:
Date.prototype.format = function(format) { var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(format)) format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o) if(new RegExp("("+ k +")").test(format)) format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); return format; } function getDay(day){ var today = new Date(); var targetday_milliseconds=today.getTime() + 1000*60*60*24*day; today.setTime(targetday_milliseconds); //注意,这行是关键代码 var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = doHandleMonth(tMonth + 1); tDate = doHandleMonth(tDate); return tYear+"-"+tMonth+"-"+tDate+" 00:00:00"; } function doHandleMonth(month){ var m = month; if(month.toString().length == 1){ m = "0" + month; } return m; } var myDate = new Date(); var datetime = myDate.format("yyyy-MM-dd 00:00:00"); var pre7day = getDay(-7); print("today="+datetime+"deleteday="+pre7day); datetime= new Date(datetime); pre7day= new Date(pre7day); var count=db.Mail.find({"updateTime":{"$lt":pre7day}}).count(); print("count="+count); db.Mail.remove({"updateTime":{"$lt":pre7day}}); print("前7天邮件清理完毕..."); exit2. 编写shell脚本mongo_clean.sh代码如下:
#!/bin/bash #清空mongodb中的前7天邮件: guoxin.ai@renren-inc.com /data/web/mongodb/mongodb-linux-x86_64-2.4.5/bin/mongo 10.3.18.80:27017/mail -quiet /data/web/email.js
注意:/data/web/mongodb/mongodb-linux-x86_64-2.4.5/bin/mongo 必须用全路径,由于使用root用户安装mongodb,但是crontab执行时候,不能直接使用
mongodb-linux-x86_64-2.4.5/bin/mongo 10.3.18.80:27017/mail -quiet /data/web/email.js,否则定时任务不会启动,由于找不到mongodb而导致。
3.加入crontab中:
10 0 * * * sh /data/web/agx/mongo_clean.sh
即完成shell操作mongodb执行定时任务,根据任务不同,修改对应的js文件。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 查看mongodb 当前任务
- 下一篇: PLSQL导出大量数据-超出excel限制,使用csv