目录

微信小程序云数据库定时清空云函数定时触发

目录

微信小程序云数据库定时清空(云函数定时触发)

需求

微信小程序云数据库某表仅保留当天数据,因此每天固定某时间清空一次

实现

1.新建云函数timer

https://i-blog.csdnimg.cn/blog_migrate/a30cba2b6ab2e508e690dfc7ed10fe80.png#pic_center

2.在timer/config.json中配置定时器

https://i-blog.csdnimg.cn/blog_migrate/e6787e114afd45892dffaeae42b90f74.png#pic_center

{
  "triggers": [
    {
      "name": "myTrigger",
      "type": "timer",
      "config": "0 25 16 * * * *"
    }
  ]
}

其中,“config”格式为“秒 分 时 日 月 星期 年”,具体配置见

按照我的设置,表示每天16:25触发一次。

3.timer/index.js中,exports.main内写需要进行的操作

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
/*********写需要进行的操作
  try{
    return await db.collection('receive').where({
      all:null
    }).remove({
      success(res){
        return res
      },
      fail(err){
        return err
      }
    })
  }catch(e){
    console.log(e)
  }
  *************/
}

若使用注释间我写的代码,注意,若想将数据库某表内容全部清空,where中应为 表中不存在的字段:null

4.在微信开发者工具中右击timer文件夹,选择“ 在外部终端窗口中打开 ”,输入命令行

npm install --save wx-server-sdk@latest

等待依赖安装完毕后,右击timer,选择“ 上传并部署:云端安装依赖(不上传node_modules) ”;再选择“ 上传触发器 ”。

至此,定时触发功能的云函数部署完毕。

4.查看云函数执行记录

打开云开发控制台,选择“云函数”一项,点击“日志”。可以看到云函数调用情况

https://i-blog.csdnimg.cn/blog_migrate/7ade48aefc11e3ea4e7947d915cba75f.png#pic_center