Reputation: 1427
I want to prevent a stall in my for loop.
import datetime as dt
shopping_list = ['eggs','milk','bread']
def buy_item(item):
connect_to_website()
send_order_instruction(item)
disconnect()
for i in range(0,len(shopping_list)):
item = shopping_list[i]
time_elapsed = 0
start_time = dt.datetime.now()
while time_elapsed < 60:
buy_item(item)
check_time = dt.datetime.now()
time_elapsed = check_time - start_time
buy_item() logs onto a website and goes through a buying procedure. But sometime it would get stuck on an item because of internet connection, item not found, website down temporarily for split second, or some other reasons. And the function simply stalls. I tried using a while loop, but that didn't work. How do I make the loop skip over an item if it stalls for more than 1 minute? Is it even possible to make the loop skip over a buy_item for a particular item? Would a try and except be appropriate in this situation? Just thinking out loud. Thank you for your help. I really appreciate it.
Upvotes: 0
Views: 121
Reputation: 4800
import threading
thread = threading.Thread(target=buy_item, args=(item,))
thread.start()
This will do async call to buy_item, you can do sys.exit() inside thread or can wait for thread to finish by using thread.join()
Better look for threading module or multiprocess module in python for async calls.
Upvotes: 1
Reputation: 20774
You don't need to code this yourself. It should be built into whatever software you use to handle HTTP requests.
For example, the requests library lets you configure this as an additional parameter to the get()
method. The old urllib2 library also has a timeout parameter. Any good HTTP client library or software will have this feature; if yours doesn't, look harder or find another piece of software.
You are likely to need a try/except to handle timeouts thrown from your HTTP software.
Upvotes: 0