1. 自动任务的功能为:
定时扫描数据库中的记录,然后发邮件
代码如下
scheduleMail.py
import pymysql import smtplib from email.mime.text import MIMEText from email.header import Header import time def sendMail(body): sender = ‘[email protected]‘ receiver = [‘[email protected]‘, ‘[email protected]‘, ‘[email protected]‘] 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<[email protected]>‘ msg[‘To‘] = "[email protected]‘, ‘[email protected]‘, ‘[email protected]" 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进程就好了
这样,整个后台任务就真的被杀死了!
时间: 2024-09-28 02:27:48