简体   繁体   中英

How can I get my Python function in Flask application to stop running?

I set up a function that is meant to be called every minute to send an email. I call it every minute using the following:

import smtplib
def messages_emailed():
    fromaddr = FROMADDRESS
    toaddrs = TOADDRESS
    msg = "this is a test message."

    username = USER
    password = PASSWORD

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()
         threading.Timer(60, messages_emailed).start() #runs func every min
    messages_emailed()

This worked perfectly, although despite me stopping the application in Terminal, using control–C , I am continuing to receive mail every minute, and refreshing the page in which my application is running in my browser, 127.0.0.1:5000 , continues to display my application. I can edit my script to add a cancel statement, but hitting save did not make any changes, and trying to reload my application in terminal returned an error

>  * Running on ``http://127.0.0.1:5000/ ``Traceback (most recent call
> last):   File "bit.py", line 79, in <module>
>     app.run()    File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py",
> line 739, in run
>     run_simple(host, port, self, **options)   File "/Library/Python/2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/serving.py",
> line 613, in run_simple
>     test_socket.bind((hostname, port))   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py",
> line 224, in meth socket.error: [Errno 48] Address already in use

For now, I have stopped the influx of emails by deleting the mail account I used to send messages from. However, I am wondering what a long term solution would look like, something that I can ideally stop from the terminal or stops executing when the program does. Research has suggested using sys.exit(0) though I do not know where in my program to place this or when it will quit the function.

Any help would be greatly appreciated.

at first you have to check formatting.

if you want to use thread, you have to write your threading manager which will be encapsulates the start() , stop() methods for your threads.

thread1 = threading.Timer(60, sender()).start()

for stopping just call thread1.stop()

It seems that your script has start a new process to rerun the email-sending function periodically. You may check the active process by running ps aux | grep python ps aux | grep python .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM