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天邮件清理完毕...');
exit
2. 编写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文件。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值