将几个线程置于睡眠状态/等待不使用Time.Sleep()

时间:2015-12-15 23:38:07

标签: python multithreading tweepy

我编写了这个函数来处理Tweepy游标的“速率限制错误”,以便继续从Twitter API下载。

def limit_handled(cursor, user):
    over = False
    while True:
        try:
            if (over == True):
                print "Routine Riattivata, Serviamo il numero:", user
                over = False
            yield cursor.next()
        except tweepy.RateLimitError:
            print "Raggiunto Limite, Routine in Pausa"
            threading.Event.wait(15*60 + 15)
            over = True
        except tweepy.TweepError:
            print "TweepError"
            threading.Event.wait(5)

由于我使用多个线程进行连接,因此当RateLimitError错误引发并在15分钟后重新启动它们时,我想停止它们中的每一个。 我之前使用过这个函数:

time.sleep(x)

但我明白这对线程不起作用(如果线程不活动,计数器不会增加)所以我尝试使用:

threading.Event.wait(x)

但是这个错误引起了:

    Exception in thread Thread-15:
Traceback (most recent call last):
  File "/home/xor/anaconda/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/home/xor/anaconda/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/xor/spyder/algo/HW2/hw2.py", line 117, in work
    storeFollowersOnMDB(ids, api, k)
  File "/home/xor/spyder/algo/HW2/hw2.py", line 111, in storeFollowersOnMDB
    for followersPag in limit_handled(tweepy.Cursor(api.followers_ids, id = user, count=5000).pages(), user):
  File "/home/xor/spyder/algo/HW2/hw2.py", line 52, in limit_handled
    threading.Event.wait(15*60 + 15)
AttributeError: 'function' object has no attribute 'wait'

我怎样才能“睡觉/等待”我的线程确保他们会在适当的时候醒来?

1 个答案:

答案 0 :(得分:2)

尝试这样做:

import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)

下次首先尝试google-ing:Issues with time.sleep and Multithreading in Python