For 循环:如何在 100 次循环后暂停它 x 秒?
For loop: How can I pause it after 100 loops for x seconds?
我有以下 for loop
:
for user_id in new_followers:
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
为了避免 API 限制,我想在每次发送 100 条直接消息时暂停循环 600 秒。
最好的方法是什么?
- 在循环中使用
counter
,最多计算 100 条消息。
当counter == 100
时,使用
from time import sleep
sleep(AMOUNT_OF_TIME)
您可以使用:
import time
然后是
time.sleep(seconds)
睡觉。您可以在小于一秒的时间内使用浮点数。
有一点要注意,如果你这样做,人们可能会讨厌你。
你可以这样做:
import time
count = 0
for user_id in new_followers:
count +=1
if count == 100:
count = 0
time.sleep(600)
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
你可以试试这个:
for i, user_id in enumerate(new_followers):
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
if (i+1)%100 == 0:
time.sleep(x) # here x in milisecond
我有以下 for loop
:
for user_id in new_followers:
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
为了避免 API 限制,我想在每次发送 100 条直接消息时暂停循环 600 秒。
最好的方法是什么?
- 在循环中使用
counter
,最多计算 100 条消息。 当
counter == 100
时,使用from time import sleep sleep(AMOUNT_OF_TIME)
您可以使用:
import time
然后是
time.sleep(seconds)
睡觉。您可以在小于一秒的时间内使用浮点数。
有一点要注意,如果你这样做,人们可能会讨厌你。
你可以这样做:
import time
count = 0
for user_id in new_followers:
count +=1
if count == 100:
count = 0
time.sleep(600)
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
你可以试试这个:
for i, user_id in enumerate(new_followers):
try:
t.direct_messages.new(user_id=user_id, text="Thanks for following. Etc etc etc")
print("Sent DM to %d" % (user_id))
followers_old.add(user_id)
if (i+1)%100 == 0:
time.sleep(x) # here x in milisecond