Use python to make the task of running Linux server daemon timed - a reminder e-mail

1. Automatic function for the task:

  Scanning timing of records in the database, and then send the message

code show as below

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 ' ) # Chinese required parameters' utf-8', single-byte characters need not   
    MSG [ ' the Subject ' ] = Header (Subject, ' UTF-. 8 ' )   
    MSG [ ' the From ' ] = ' XXX <[email protected]> '     
    MSG [ ' the 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 ' server the IP ' , = user ' database username ' , the passwd = ' database password ' , DB = ' database name ' , Port = 3306, charset = ' UTF8 ') 
    A = 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 Line mailBody + + = Separator 
    
    Print ( ' message body: S% ' % mailBody)
     IF (mailBody =! "" :) 
        The sendMail (mailBody) 
    the else :
         Print ( " no E-mail " ) 

DEF main ():
     the while (True ): 
        the time.sleep ( 1800 ) 
        ScanLogic () 

main ()

 

2. put it into a shell script as a background task

scheduleMail.sh

#!/bin/bash
cd /home/yourfolder
python -u scheduleMail.py

 

3. How to Kill background tasks

Here is a pit, a lot of online blog did not say, I mention here, lest they repeat to step on.

Kill the task, like kill process as traditional Linux

ps aux|grep scheduleMail
Here you will see the process number, then use the command kill -9 scheduleMail can kill the process
 
However, you will find that although the process of killing, background task is still running.
why?
You will kill you just the daemon shell scripts.
Here, you need to use the command ps -e view all processes,
Found that there python process is running, kill the process like a python
In this way, the whole background tasks really been killed!
 

Reproduced in: https: //www.cnblogs.com/davidgu/p/7617102.html

Guess you like

Origin blog.csdn.net/weixin_34327761/article/details/93803143