我已经设置了一个 python 脚本来在表中插入一条新记录,发送一封电子邮件并在成功发送电子邮件后更新最近插入的记录。Python脚本如下:
import smtplib
import pyodbc
import time
import os
import time
from smtplib import SMTPException
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
localtime = time.asctime( time.localtime(time.time()) )
fromAddress = "sender@mydomain.com"
toAddress = "myEmail@mydomain.com"
email = MIMEMultipart()
email['From'] = fromAddress
email['To'] = toAddress
connection = pyodbc.connect('DRIVER={SQL Server};SERVER=mySQLServer;DATABASE=mydb;UID=username;PWD=password')
cursor = connection.cursor()
query = "INSERT INTO [mydb].[dbo].[Logger] ([ScriptStartTime], [EmailSent?]) VALUES (CURRENT_TIMESTAMP, 0);"
cursor.execute(query)
print "************************Python Script Log Started at", localtime,"**********************"
def update():
updateEmailFlagQuery = ("UPDATE [mydb].[dbo].[Logger] SET [EmailSent?] = 1, [EmailSentTime] = CURRENT_TIMESTAMP WHERE ID = (SELECT MAX(ID) FROM [mydb].[dbo].[Logger])")
updateEmailFlag = cursor.execute(updateEmailFlagQuery)
connection.commit()
def notify(email, body, fromAddress, toAddress):
email['Subject'] = "It Worked"
email.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('SMTPServer', 25)
server.set_debuglevel(True)
text = email.as_string()
server.sendmail(fromAddress, toAddress, text)
server.quit()
connection.commit()
try:
body = "This is an Email sent from Scheduled Python Script"
notify(email, body, fromAddress, toAddress)
print "Email Sent successfully"
try:
update()
print "Update Statement on Success code-block executed successfully
except:
connection.rollback()
print "Update Statement failed and update Transaction Rolled back"
except SMTPException, e:
print e+" SMTP ERROR OCCURED"
except Exception, e:
print e
print "Unexpected Error/Exception";
print "************************Python Script Log Ended at", localtime,"**********************"
此脚本计划通过 Windows 任务计划在 EC2 实例上运行。这个脚本通常工作得很好,但偶尔会吐出一条错误消息。错误信息如下:
************************Python Script Log Started at Thu Jun 07 03:40:04 2018 **********************
[Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Unexpected Error/Exception
************************Python Script Log Started at Thu Jun 07 03:40:04 2018 **********************
我试图复制这个错误但失败了。经过观察,我发现失败与失败时没有用户活动之间存在高度相关性。该脚本仅在 EC2 机器上没有最近的用户活动时才会失败。有没有人遇到过类似的事情?或任何建议/改进?
如果有任何缩进错误,请原谅,可能是由于我在将脚本复制到 StackOverflow 的降价时手动格式化。