1. 自動任務的功能為:
定時掃描數據庫中的記錄,然后發郵件
代碼如下
scheduleMail.py
import pymysql import smtplib from email.mime.text import MIMEText from email.header import Header import time def sendMail(body): sender = 'xxx@163.com' receiver = ['abc@xxx.com', 'def@xxx.com', 'ghi@xxx.com'] subject = '郵件主題' smtpserver = 'smtp.163.com' username = 'your username' password = 'your password' msg = MIMEText(body,'plain','utf-8') #中文需參數‘utf-8',單字節字符不需要 msg['Subject'] = Header(subject, 'utf-8') msg['From'] = 'xxx<xxx@163.com>' msg['To'] = "abc@xxx.com', 'def@xxx.com', 'ghi@xxx.com" smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() def scanLogic(): conn = pymysql.connect(host='服務器IP', user='數據庫用戶名', passwd='數據庫密碼', db='數據庫名', port=3306, charset='utf8') cur = conn.cursor() sql = "select * from ..." cur = conn.cursor() cur.execute(sql) alldata = cur.fetchall() mailBody = "" separator = "----------------------------------------------\n" for rec in alldata: field1 = rec[0] field2 = rec[1] line = "field1: %s \t field2: %s \n" % (field1, field2) mailBody = mailBody + line + separator print('郵件正文: %s' % mailBody) if (mailBody != ""): sendMail(mailBody) else: print("無可發送郵件") def main(): while (True): time.sleep(1800) scanLogic() main()
2. 把它做成后台任務的shell腳本如下
scheduleMail.sh
#!/bin/bash cd /home/yourfolder python -u scheduleMail.py
3. 如何殺死后台任務
這里有個坑,很多網上的博客沒有說,我在這里提一下,以免大家重復去踩。
殺死該任務,就像殺死傳統Linux進程一樣
ps aux|grep scheduleMail
這里你會看到進程號,然后使用命令kill -9 scheduleMail就可以殺死該進程
但是,你會發現,進程雖然殺死了,后台任務仍在運行。
為什么呢?
你會你只是殺死了shell腳本的后台進程。
這里,你需要使用命令ps -e查看所有進程,
發現還有python進程在運行,殺死該python進程就好了
這樣,整個后台任務就真的被殺死了!