Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud development timed triggers


May 22, 2021 Mini Program Cloud Development Advanced



Anything that can produce events that trigger the execution of a cloud function can be called a trigger, depending on the time trigger can handle periodic things, such as times, daily newspapers, weekly reports and other notification reminders, but also can handle countdown tasks, such as holidays, anniversaries and you can specify a specific time countdown task, in addition, timed triggers can also be used to periodically handle some timed tasks. For example, clean up unnecessary data on a regular basis and update the data within the collection on a regular basis.

First, the use of timed trigger instructions

1, the configuration and deployment of timed triggers

Cloud functions with timed triggers are automatically triggered at the appropriate point in time, and the return results of the cloud functions are not returned to the caller. Before using a timed trigger on a cloud function, the first step is to ensure that the cloud function can be called successfully on the small terminal and, more accurately, that the cloud test in the cloud development console can be debugged without passing in parameters (the small terminal calls have a login state).

The confeg.json file in the cloud function directory can be used to configure permissions and time triggers, and if you don't have this profile below the cloud function directory, you can create one yourself, creating the structure directory as follows:

  1. test //云函数目录
  2. ├── config.json //权限和定时触发器等的配置文件
  3. ├── index.js //云函数
  4. ├── package.json //云函数的依赖管理

Then come in the configuration fileconfig.json similar to how to format the configuration, config.json strictly follow the format required by the configuration , such as the last item of the array can not have a comma, the configuration file can not have comments, etc

  • The triggers field is an array of triggers, but at present the cloud function supports only one trigger, i.e. the array can only fill in one, not add more than one;

  • Name is the name of the trigger, with a maximum support of 60 characters, support for a-z, A-Z, 0-9, - and , which must begin with a letter;

  • Type is a trigger type, and timer is a time trigger

  • config is the timed configuration of the trigger, which is the cron expression (described later), cron has seven required fields, not much or less (the following is triggered every 5 seconds from 9 a.m. to 12 a.m.);

  1. {
  2. "triggers": [
  3. {
  4. "name": "tomylove",
  5. "type": "timer",
  6. "config": "*/5 * 9-12 * * * *"
  7. }
  8. ]
  9. }

When we modify the trigger profile confeg.json, first right mouse button confeg.json select "cloud function incremental upload: update file", and then right-click confeg.json select "upload trigger". H ere, "Cloud Function Incremental Upload: Update File" is to update the trigger file on the cloud function side, while "Upload Trigger" lets the trigger take effect. I f the trigger on the cloud function side is not updated to "upload trigger" to execute the timed trigger, the file may not be updated, executed or the old trigger content. When we want to pause or delete a trigger, we can right-click Delete Trigger.

2, Cron expression syntax

Cron expression has seven required fields, separated by spaces, neither more write nor less write, each field has its meaning corresponding to a different point in time, the expression is taken as an integer and the range of the time system (note the month before the week):

First place Second place Third place Fourth place Fifth place Sixth place 7th place
Seconds (0-59) Minutes (0-59) Hours (0-23) Day (1-31) Month (1-12 or three-letter abbreviation) Week (0-6 or three-letter abbreviation) Year (1970-2099)

Here's a case of a cron expression, and what we need to know about wildcards in cron expressions and what it means to write numbers directly:

  • , , which represents a set, meaning "and" in the expression of time, for example, in the 1,2,3 2 and 3 points;

  • - , all values of the specified range, which means "to" in the expression of time, for example, in the 1-15 to 15th of the specified month;

  • * , which represents all values, means "per" in the expression of time, for example in the "hours" field, * hourly;

  • / , specify the step length, in the expression of time is the meaning of "separate", for example, in the "seconds" field, the */5 means every 5 seconds;

  • Write the number directly, which means "first" (point in time) in the expression of time, for example, in the "month" field, 5 day of each month;

  1. //表示每隔5秒触发一次,
  2. */5 * * * * * *
  3. //表示在每月的1日的凌晨2点触发
  4. 0 0 2 1 * * *
  5. //表示在周一到周五每天上午10:15触发
  6. 0 15 10 * * MON-FRI *
  7. //表示在每天上午10点,下午2点,4点触发
  8. 0 0 10,14,16 * * * *
  9. //表示在每天上午9点到下午5点内每半小时触发
  10. 0 */30 9-17 * * * *
  11. //表示在每个星期三中午12点触发
  12. 0 0 12 * * WED *

The Cron syntax of timing triggers does not do this every 90 seconds or 90 minutes because 90 seconds exceeds the time limit of 60 seconds, and cron cannot cover all time on span combinations such as 90 seconds combining seconds and minutes; The overlay of the triggers, the relationship between the two as or when both values are specified in the Day and Week fields in the Cron expression, i.e. the conditions for both are in effect, and it is worth noting that the time trigger is timed for the time trigger even though the time zone of the cloud function is the UTC-0 time zone.

Second, the cloud function is called with a timed trigger

The use of timed triggers is simple, using developer tools to create a new cloud function, such as trigger, and then .js the following code in the index:

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: cloud.DYNAMIC_CURRENT_ENV,
  4. })
  5. exports.main = async (event, context) => {
  6. console.log(event)
  7. return event
  8. }

Then create one in the trigger cloud function directory (if you don't have this file), and then enter the following triggers, which we can trigger every 5 seconds for debugging convenience:

  1. {
  2. "permissions": {
  3. "openapi": [
  4. ]
  5. },
  6. "triggers": [
  7. {
  8. "name": "tomylove",
  9. "type": "timer",
  10. "config": "*/5 * * * * * *"
  11. }
  12. ]
  13. }

Then right-click index.js and confeg.json, select "Cloud function incremental upload: update file", and then right-click confeg.json to select "upload trigger". Cloud functions are automatically triggered every 5 seconds, and the relevant logs can be viewed in the developer tool's cloud development console and Tencent's cloud development web console's cloud function logs.

Note that the small terminal calls the object returned by the trigger cloud function, and different from the object returned with the timing trigger, the timed trigger trigger cloud function is not available for openId, and here is a Time time when the time zone is UTC-0, 8 hours later than Beijing time:

  1. //在小程序端调用trigger云函数之后返回的event对象
  2. {
  3. "userInfo":{
  4. "appId":"wxda99******7046",
  5. "openId":"oUL-m5F******buEDsn8"
  6. }
  7. }
  8. //使用定时触发器触发云函数之后返回的event对象
  9. {
  10. "Message":"",
  11. "Time":"2020-06-11T11:43:35Z",
  12. "TriggerName":"tomylove",
  13. "Type":"timer",
  14. "userInfo":{
  15. "appId":"wxda99********46"
  16. }
  17. }

Third, the application of timed triggers

Timed triggers are widely used, and here are just a few common examples to illustrate:

1, combined with message push

Message push here is not just about subscribing to messages, but also about unified service messages, public number messages (you can use cloud functions to develop WeChat public numbers), notifications developed in small programs yourself (only users can see when they open small programs), email messages, and so on.

For example, if a user subscribes to a periodic notification reminder such as a daily newspaper, weekly newspaper, monthly report, etc., or we need to send some summary information to the user, we can write a timed trigger, for example, we need to send a working weekly report to the specified user, and get the data from the database at 17:30 p.m. every Friday, cron expression is written as follows:

  1. * 30 17 * * FRI *

It can also be used to handle tasks that count down (a specified point in time), such as holidays, anniversaries, and some active time nodes (time triggers currently can only be used for one cloud function with one trigger, but can be managed in advance), such as we want to call a cloud function at 9 a.m. on Children's Day to send messages to a specified user base:

  1. 0 0 9 1 6 * *

Of course, such a specific point in time seems too inflexible, but if you combine time with the cloud development database, the flexibility will be much greater, for example, in operation every morning at 11 o'clock is the most accessed point in time for your users, you only need to write a cloud function, all activities are pushed at this point in time, so that the time trigger is triggered at this point in time every day, there is activity (there is data in the database) will send a message, if not not (cloud function call once the cost is very low).

If it's real-time data, we can also turn up the frequency of the timed trigger, triggering every 5 seconds, for example, as long as our database has the latest data, it will send a message to the designated user. A lthough not completely real-time, the five-second frequency and real-time are not much different. You can also adjust the frequency of triggers depending on the situation, after all, the frequency of 5 seconds and 1 minute does not make much difference to the user's experience, but the cost is 12 times the relationship.

You may also want to trigger cloud functions during a specified time period, such as when you only want to trigger on weekdays, or between 9 a.m. and 18 p.m., and to trigger at a specified time period that can either make the trigger more accurate or cost-effective, such as the following triggers are triggered every 5 seconds during the 9 a.m. to 12 p.m. and 14 p.m. to 18 p.m. on weekdays.

  1. */5 * 9-12,14-18 * MON,TUE,WED,THU,FRI *

From the above case we can learn that the timing trigger of the cloud function can come from the configuration of the cron expression, we can specify the point-in-time period and frequency to achieve the desired effect, and this time "can also come from the configuration of the database" (disguise), meaning that we can set the trigger time period or frequency, if there is data in the database to send, no data to send, so that we can achieve the flexibility of the trigger in time.

2, real-time access to data

Sometimes our data does not come from the database, but from third-party services, such as the previously described history of today's APIs, weather APIs, knowledge of the daily API and so on, as well as some webhook, these APIs and third-party services provide files in json format, API data will be updated at any time, but they are updated but do not actively notify us, then we can use the timed trigger to make a request to these APIs, If the data is updated, we can store the updated data in our database or do other processing, such as robotic notification services such as enterprise WeChat's robots.

Of course, the data obtained on a regular basis can also be reptiles, such as we can regularly crawl the news of the specified keywords or the dynamics of the designated website, when the reptiles get different data, the latest updates in a robot message or other way to process in a timely manner.

That is, we can't monitor changes in third-party APIs or website data in real time, but we can use a timed trigger to initiate a request or crawl data, through data changes to achieve "real-time" access to data.

3, automated processing

In the design of the database, we mention that sometimes the database data need to be regularly backed up and deleted and other clean-up and maintenance work, such as more than a certain amount of time logs, with a strong timeliness of active data, as well as for performance considerations to do false deletion (database performance and optimization is described), after all, the database has a certain storage costs and too much useless data will also affect the performance of the database, we can write a cloud function with a time trigger to perform such tasks.

We can also handle some of the tasks that consume cloud functions, database performance, such as image auditing and cropping, acronyms, etc., whether user comments contain sensitive words (although securely processed, but sometimes we also set special sensitive words), summary of data, deletion of discarded files in cloud storage, integrity of user information, and so on.

That is, combined with timed triggers, we can automate the processing of some tasks.

4, intensive task diversion

We know that cloud functions have some limitations when dealing with some complex tasks, one is the time limit for execution, it is recommended that the execution time at setup should not exceed 20s, the maximum time should not exceed 60s; Exporting millions of data to Excel, sending hundreds of thousands of subscription messages or messages, and so on, can be processed with a timed trigger.

With timed triggers, we can batch tasks that take a long time, require high levels of complexity, and database requests, such as sending mail to 1 million people: the cloud function initiates a database request, requesting only 1,000 unsended users at a time (querying a field with the where condition) For status:false then send the message to 1,000 people (you can refer to the previous message), send the message, and mark the 1,000 data (such as using update instructions to change the status to true), so that the next time you query the user who has not sent the message, you won't repeat it. With a timed trigger, send tasks are performed every 2 seconds and can be processed in tens of minutes.