Im trying to run send an email with a delay, since the conditional to send the email can be ON for quite some time and I dont want to receive and infinite amount of email alerts...
For this I'm trying the threading.timer to give it a delay and only send the email every 15 minutes... I tried the long 900 second delay on the .timer object and it works (used time script)... but when I run it to send the email it first sends the email and then enters the timer not running the other parts of the script... The email function works just fine... running python 2.6.6
#!/usr/bin/env python
import time
import smtplib #for sending emails when warning
import threading
if True: #the possibility exists that the conditional is met several times thus sending lots of emails
t = threading.Timer(300,send_email('Tank temperature Overheat',tank_temp))
t.start() # after 300 seconds, the email will be sent but the script will keep running
print "rest of the script keeps running"
print "keeps running the scrpit and after 300s the email is sent"
Any ideas on why its not working or another workaround?
After playing with it... it does the sleep but the sends all the emails... not one email every X amount of .time set... i.e.
n=300
start = time.time()
while (time.time() - start < n):
led_temp = 56
if led_temp > 55:
t = threading.Timer(100, lambda: send_email('Lights temperature Overheat',led_temp))
t.start()
Instead of receiving one email every 100 seconds I get 36 emails after 300 seconds .. ?? Any idea why? (Reformat from comment below)
After reading the answer on the threading I understood the problem... Im still knew to python and had never user threading so I guess that was the root cause of the 36 emails I received when creating endless amounts of threads... I fixed it by using a flag, and tested the code like this:
def raise_flag():
global start
interval = 300
if start > interval:
start = 0
flag = True
print "Flag True, sending email"
return flag
else:
flag = False
start = start + 1
print "Flag OFF", start
time.sleep(1)
return flag
led_temp = 27
while led_temp > 26:
flag = raise_flag()
if flag:
send_email('Tank temperature Overheat',led_temp)
flag = False
print "Sent email"