• 利用python制作在Linux服务器后台定时运行的任务-邮件提醒


    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 = "----------------------------------------------
    "
        for rec in alldata:
            field1 = rec[0]
            field2 = rec[1]
            line = "field1: %s 	 field2: %s 
    " % (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进程就好了
    这样,整个后台任务就真的被杀死了!
     
  • 相关阅读:
    brew一直卡在Updating Homebrew的解决办法
    ELK5.6.4+Redis+Filebeat+Nginx(CentOS7.4)
    CentOS7.3 ffmpeg安装
    nginx Dockerfile
    pip安装第三方包超时
    logrotate nginx日志切割
    Ansible部署zabbix-agent
    Zabbix主动模式和被动模式
    Zabbix添加监控主机
    Zabbix3.2安装
  • 原文地址:https://www.cnblogs.com/davidgu/p/7617102.html
Copyright © 2020-2023  润新知