设立个定时器,监控数据库里fb_state(发布状态),并将数据库中一条记录的开始时间与截止时间和当前时间进行比对。若当前时间在开始时间与结束时间之间,则将发布状态设为1,否则为0.

同时,将此段代码放到router里的init函数里,这样每次运行程序时都会启动此方法,并且直至程序中断才停止监控。

(使用的是Beego框架)

//监控已发布的contents
func MonitorValidtimes() {
    log.Info("后台状态监控已开启")
    var PostFb, PreFb []orm.Params

    o := orm.NewOrm()

    T := time.Tick(time.Second)
    for now := range T {
        o.Raw("SELECT id,end_time FROM dt_content WHERE fb_state=?", 1).Values(&PostFb)
        o.Raw("SELECT id,start_time,end_time FROM dt_content WHERE fb_state=?", 0).Values(&PreFb)
        i, j := 0, 0

        //监控已发布contents
        for range PostFb {
            end_time := PostFb[i]["end_time"]
            id := PostFb[i]["id"]
            et, _ := strconv.ParseInt(end_time.(string), 10, 64)
            idi, _ := strconv.ParseInt(id.(string), 10, 64)
            if et <= now.Unix() {
                o.Raw("Update dt_content SET fb_state=0 WHERE id=?", idi).Exec()
            }
            i++
        }

        //监控未发布contents
        for range PreFb {
            start_time := PreFb[j]["start_time"]
            end_time2 := PreFb[j]["end_time"]
            id2 := PreFb[j]["id"]
            st, _ := strconv.ParseInt(start_time.(string), 10, 64)
            et2, _ := strconv.ParseInt(end_time2.(string), 10, 64)
            id2i, _ := strconv.ParseInt(id2.(string), 10, 64)
            if st <= now.Unix() && now.Unix() < et2 {
                o.Raw("Update dt_content SET fb_state=1 WHERE id=?", id2i).Exec()
            }
            j++
        }

    }
}

 

版权声明:本文为basque原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/basque/p/5146372.html