How to run a python program in background and execute after every given time ( like after five minute )


(Nehat Khan) #1
from twilio.rest import Client 
import requests
import lxml
import bs4

res = requests.get('https://www.brainyquote.com/quote_of_the_day')
soup = bs4.BeautifulSoup(res.text, 'lxml')
qod = soup.select('title')
sms= (qod[0].text)



account_sid= 'xxxxxxxxxxxxxxxxx'
auth_token = 'xxxxxxxxxxxxxxxxx'
client = Client(account_sid, auth_token)
message = client.messages.create(
					body = sms,
					from_ = '+111111111',
					to = '+222222222222'
	)
print(message.sid)

I want to execute this program after every five minutes and send me an SMS to given mobile no.


(Vitor Freitas) #2

The most simple solution would be just creating a cron job (considering this script is saved in a linux server)

*/5 * * * * /usr/bin/python /opt/sms_script.py

For the cron job you will need to specify the full path of your Python installation and where the script is saved

You can read more about how to setup it here:

https://www.ostechnix.com/a-beginners-guide-to-cron-jobs/

If you are on Windows you can explore some options in this StackOverflow thread: What is the Windows version of cron?


Another option is to use Twisted

Here is a minimal example:

from twisted.internet import task
from twisted.internet import reactor

FIVE_MINUTES = 5 * 60


def send_sms():
    # Your code here
    pass


def main():
    task.LoopingCall(send_sms).start(FIVE_MINUTES)
    reactor.run()

if __name__ == '__main__':
    main()

Then you can run this script on the background:

nohup python sms_script.py