擅长:python、mysql、java
<p>线程是一种很好的方法。要暂停函数,请使用<a href="https://docs.python.org/2/library/time.html#time.sleep" rel="nofollow noreferrer">^{<cd1>}</a>(基于<a href="https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python">How can I make a time delay in Python?</a>):</p>
<pre><code>import time, random
# Time range to sleep, in seconds
def randomWait():
sleepMin = 1.0
sleepMax = 5.0
time.sleep(random.uniform(sleepMin, sleepMax))
def do_action1(*args):
print("something")
# do something else
randomWait()
print("something")
print("else")
randomWait()
</code></pre>
<p>我在这个例子中使用了<a href="https://docs.python.org/2/library/random.html#random.uniform" rel="nofollow noreferrer">^{<cd2>}</a>,但是您可以随意地使用<a href="https://docs.python.org/2/library/random.html" rel="nofollow noreferrer">^{<cd3>}</a>模块或任何其他您喜欢的东西来设置区间的随机性。在</p>
<p>线程解决方案将允许不同的操作同时运行。如果不允许这样做,请使用一个线程并按照user1827356的建议使用<code>yield</code>:</p>
^{pr2}$
<p>请注意,在本例中,您的操作是生成器。它们基本上是运行您定义的代码的对象,并在每次碰到<code>yield</code>关键字时存储状态(暂停)。对于单线程应用程序,这可能是最好的方法。在</p>