thread_num = 12# 并行的线程数,如果是并行函数是CPU密集型,设为CPU线程数最好 thread_list = [] for i inrange(thread_num): thread_list.append(myThread(myfunc, (a, b, c))) for i inrange(thread_num): thread_list[i].start() # 启动线程 for i inrange(thread_num): thread_list[i].join() # 同步操作,等待所有线程结束
import time TIME = 0 for i inrange(10): if time.time() - TIME < 1: time.sleep(max(0, 1 - (time.time() - TIME))) TIME = time.time() response = requests.post(url_add, data = data[i]) # 发送数据,调用API
但是有时侯还是会遇到调用失败,所以需要额外加一个失败重传:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import time TIME = 0 for i inrange(10): whileTrue: try: if time.time() - TIME < 1: time.sleep(max(0, 1 - (time.time() - TIME))) TIME = time.time() response = requests.post(url_add, data = data[i]) # 发送数据,调用API req_con = response.content.decode('utf-8') # 答复数据 req_dict = json.JSONDecoder().decode(req_con) result = req_dict['result'] except KeyError: # 如果调用失败,答复数据为空,字典req_dict按键取值会出现KeyError print('retrying...') continue# 如果失败,重新开始 break# 如果成功,跳出循环