Small program cloud development-Cloud function timing trigger configuration

Mini Program Cloud Development-Cloud function timing trigger configuration

Create a new cloud function timer, the applet will create two new files index.js and package.json

The effect of the timing trigger is equivalent to the following piece of code. The timing trigger cannot pass parameters, and the parameters need to be written in the cloud function.

wx.cloud.callFunction({
	name:'timer'
})

This article takes timing refresh access_token as an example

1. Cloud function content

index.js

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

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
var request = require('request')
// 定时器
exports.main = async(event, context) => {
  const appkey = '';
  const appsecret = '';
  var url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + appkey + '&client_secret=' + appsecret;
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: "POST",
      json: true,
      headers: {
        "content-type": "application/json",
      },
    }, function(error, response, body) {

      if (!error && response.statusCode == 200) {
        console.log('通行证为' + body.access_token)
        resolve(body.access_token)
        //更新数据库中的access_token
      }
    })
  })
}

Now that the cloud function function has been implemented, the trigger needs to create a new config.json configuration file under the timer folder.

The config.json file is the core file of trigger configuration. The content of the file is as follows. For specific matching rules, please refer to the official documentation.

This code rule is triggered every day at two in the morning.

config.json

{

  "triggers": [
    {

      "name": "myTrigger",

      "type": "timer",

      "config": "0 0 2 * * * *"
    }
  ]
}

2. The deployment process

  1. Select the overall timer function-> create and deploy (cloud installation dependencies)
  2. Select the config.json file separately-> upload trigger

3. Effect display

Guess you like

Origin www.cnblogs.com/masterchd/p/12722325.html