Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Cloud function Timer trigger based on Serverless to realize automatic timing sign-in every day

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces how to use cloud function Timer trigger to clock in automatically every day based on Serverless. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

I don't know if you have ever encountered the demand for regular clocking in, such as commodity seconds, train tickets on sale on a regular basis, daily health punch, and so on. At this time, we can often through some technical means, write some automatic operation script, to achieve timing automatic sign-in operation.

Of course, I do not discuss how to write automated operation scripts, but I will introduce how to use Timer triggers of Tencent Cloud functions to implement scheduled tasks to achieve some fancy operations (coquettish operations) quickly, stably and cheaply.

Effect display

Daily health information is updated automatically

Daily timed data report

As you can see, scheduled tasks with mailboxes to send cloud function running results are quite comfortable to use, and you can also make yourself a daily gadget such as science and technology information push and data reports to entertain yourself. For other uses, please open your brains and make up for them by yourself.

Practical practice course 1. Create a new cloud function

We choose python3 for the running environment, select scheduled test for template function, and then click next.

The description of the template function says, "the function of this sample code is to dial the address in the URL list regularly and send an alarm by email."

And this is exactly what we want to implement, but there is a problem with the email delivery of this template function, which we will explain in detail later.

two。 Template function analysis

Let's analyze this sample code

#-*-coding: utf8-*-import sysimport ossys.path.insert (0, os.path.dirname (os.path.abspath (_ file__)) + "/..") import loggingimport jsonimport requestsfrom email.mime.text import MIMETextfrom email.header import Headerimport smtpliblogger = logging.getLogger () logger.setLevel (logging.DEBUG) # Third-party SMTP service for sending alert emails. Third-party SMTP service, used to send alarm email mail_host = "smtp.qq.com" # SMTP server, such as QQ mailbox, need to open SMTP service in the account. SMTP servers, such as QQ Mail, need to open the SMTP service mail_user = "XXXXXXXXX@qq.com" # Username user name mail_pass = "*" # Password, SMTP service password. Password, SMTP service password mail_port = 465 # SMTP service port. SMTP service port # The URL address need to dial test. The URL address test_url_list = ["http://www.baidu.com"," http://www.qq.com", "http://wrong.tencent.com"," http://unkownurl.com"]# The notification list of alert emails. Alarm email notification list email_notify_list = {"XXXXXXXXX@qq.com", "XXXXXXXXX@qq.com"} def sendEmail (fromAddr, toAddr, subject, content): sender = fromAddr receivers = [toAddr] message = MIMEText (content, 'plain',' utf-8') message ['From'] = Header (fromAddr,' utf-8') message ['To'] = Header (toAddr,' utf-8') message ['Subject'] = Header (subject) 'utf-8') try: smtpObj = smtplib.SMTP_SSL (mail_host, mail_port) smtpObj.login (mail_user, mail_pass) smtpObj.sendmail (sender, receivers) Message.as_string () print ("send email success") return True except smtplib.SMTPException as e: print (e) print ("Error: send email fail") return Falsedef test_url (url_list): errorinfo = [serverless] for url in url_list: resp = None try: resp = requests.get (url) Timeout=3) print (resp) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) Requests.exceptions.ConnectTimeout) as e: logger.warn ("request exceptions:" + str (e)) errorinfo.append ("Access" + url + "timeout") else: if resp.status_code > = 400: logger.warn ("response status code fail:" + str (resp.status_code)) errorinfo.append ("Access" + url + "fail" Status code: "+ str (resp.status_code) if len (errorinfo)! = 0: body ="\ r\ n ".join (errorinfo) subject =" Please note: PlayCheck Error "for toAddr in email_notify_list: print (" send message [% s] to [% s] "% (body, toAddr)) sendEmail (mail_user, toAddr, subject, body) def main_handler (event) Context): test_url (test_url_list) if _ _ name__ = ='_ main__': main_handler (",")

Here, let's talk about the execution entry of cloud function.

The default entry for this template function is main\ _ handler (event, context).

This entry function can be configured by itself, and the specific configuration method can be found in the official documentation.

Def main_handler (event, context): test_url (test_url_list)

In addition, the main function entry of the py file here can actually be defaulted. It should be added here to facilitate local debugging and running functions.

If _ _ name__ = ='_ _ main__': main_handler (",")

Then take a look at the import section of the dependent library

Import requestsfrom email.mime.text import MIMETextfrom email.header import Headerimport smtplib

Note that there is an import requests, but there is no requests library in the local file, which means that the requests library has been installed in the running environment of Tencent Cloud functions, and there is no need for us to manually upload and add requests dependencies.

Def test_url (url_list): errorinfo = [serverless] for url in url_list: resp = None try: resp = requests.get (url, timeout=3) print (resp) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError Requests.exceptions.ConnectTimeout) as e: logger.warn ("request exceptions:" + str (e)) errorinfo.append ("Access" + url + "timeout") else: if resp.status_code > = 400: logger.warn ("response status code fail:" + str (resp.status_code)) errorinfo.append ("Access" + url + "fail" Status code: "+ str (resp.status_code) if len (errorinfo)! = 0: body ="\ r\ n ".join (errorinfo) subject =" Please note: PlayCheck Error "for toAddr in email_notify_list: print (" send message [% s] to [% s] "% (body, toAddr)) sendEmail (mail_user, toAddr, subject, body)

The idea of the test\ _ url function here is very clear. First, request the target web page in url\ _ list. If the request times out or an error code occurs, the errorinfo will be recorded.

The sendEmail function will be called when the errorinfo list is not empty, that is, when there is a problem with linked access.

Def sendEmail (fromAddr, toAddr, subject, content): sender = fromAddr receivers = [toAddr] message = MIMEText (content, 'plain',' utf-8') message ['From'] = Header (fromAddr,' utf-8') message ['To'] = Header (toAddr,' utf-8') message ['Subject'] = Header (subject,' utf-8') try: smtpObj = smtplib.SMTP_SSL (mail_host Mail_port) smtpObj.login (mail_user, mail_pass) smtpObj.sendmail (sender, receivers, message.as_string ()) print ("send email success") return True except smtplib.SMTPException as e: print (e) print ("Error: send email fail") return False

The sendEmail function is responsible for logging in to the mailbox and sending errorinfo email reminders

SmtpObj = smtplib.SMTP_SSL (mail_host, mail_port) smtpObj.login (mail_user, mail_pass) smtpObj.sendmail (sender, receivers, message.as_string ())

Next, let's take a look at the configuration file of cloud function.

Note the part of the intention that draws a red circle

"CronExpression": "* / 1 *"

This is the Cron expression, which is used to describe the execution time of scheduled tasks.\ * / 1\ * here means that the cloud function is executed every minute to achieve the function of website monitoring and dialing testing. For more information on the use of Cron expressions, please refer to the Tencent Cloud official documentation.

The above is the workflow of the cloud function of the whole dialing test example. Let's write our own cloud function according to the gourd drawing ladle.

3. Request data analysis

The favorite bag grabbing session to see what the mobile app communicates with the server when signing in.

Click in to have a look.

OK, here we have seen the login process of the application. Here, we have submitted three parameters, username,password and type, corresponding to our user name, login password and user type, respectively. Later, we just need to re-send these data to the server to simulate login to App.

Here is to send the health information we filled in to the server, which we will throw back to the server later.

4. Write cloud function

According to the above analysis, go directly to the code

Def myHealth (user, pwd, email): errorinfo = [serverless] s = requests.Session () # New request object data = {# login information 'username': user,' password': pwd, 'type':' student',} r = s.post (server+'/authentication/login' Json=data) # Log in to if r.json () ['ok']: errorinfo.append (' login succeeded') else: s.close () errorinfo.append ('login failed') return data = {# health information "home": "at home", "address": "", "keepInHome": "No", "keepInHomeDate": 'null' "contact": "No", "health": "No", "familyNCP": "No", "fever": "No", "feverValue": "", "cough": "No", "diarrhea": "No", "homeInHubei": "No", "arriveHubei": "none", "travel": "none" "remark": "none", "submitCount":'0'} r = s.post (server+'/student/healthInfo/save' Json=data) # submit health information if r.json () ['ok']: errorinfo.append (' submitted health information successfully') else: errorinfo.append ('failed to submit health information:' + r.json () ['message']) s.close () # close connection emailTask (errorinfo, email) # send email

Well, replace the test\ _ url function in the template function and ok it.

However, I mentioned earlier that there was a problem with email delivery. Let's take a look at the email content coding part of the sendemai function.

Message ['From'] = Header (fromAddr,' utf-8') message ['To'] = Header (toAddr,' utf-8') message ['Subject'] = Header (subject,' utf-8')

The recipient, sender, and subject information here are all encoded by Header (string, 'utf-8'). However, when I use the 163 mailbox to send a letter, this method can only send email to my own mailbox, and sending it to others will be regarded as spam by the mail system and fail. So if you need to send an email to another mailbox, you need to remove the code and change it to

Message ['From'] = fromAddr message [' To'] = toAddr message ['Subject'] = subject

So that the mail can be sent normally.

5. Set trigger

OK, let's save the modified cloud function.

Then change the memory to 64mb, and give a timeout of 3 seconds.

Finally, a timing trigger is added, and here we select a custom trigger cycle.

The Cron expression 006\ * means that it is triggered at 6 o'clock every morning. Be careful not to write it as\ *\ * 6\ *, otherwise it will be triggered every second at 6-7 o'clock every day. In that case, the picture is too beautiful to imagine, ha ~

This is all about how to use cloud function Timer triggers to automatically clock in every day based on Serverless. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report