Python随机循环

2024-04-25 14:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,基本上在while循环中执行:

while 1:
  <do stuff>

我想做的是让它随机执行一个动作,大约每小时一到两次。在

我试过如果随机。随机()>;5:但这种事太频繁了。在

有什么办法可以保证它每小时响一到两次而不经常响吗?在


Tags: gt脚本do小时动作stuffwhile办法
3条回答

如果你有一个时间窗口,那可能是一个很好的选择应用睡眠间隔。在

例如,您可以:

from time import sleep
from random import randint

while 1:
  <do stuff>
  sleep(randint(0, 3600))

使用随机数发生器为操作创建运行时间。这不会阻止循环中的其他操作。在

import time
import random

def get_new_time_to_perform_action():
  delay_minutes = (30 + random.random() * 30) # 30-60 minutes
  return time.time() + delay_minutes * 60

next_time_to_run = get_new_time_to_perform_action()

while True:
  if (time.time() >= next_time_to_run):
    # <do action>
    next_time_to_run = get_new_time_to_perform_action()
  # <do other actions>

为了控制每小时的重复次数,我建议用random.randint选择一个整数,然后选择事件在一小时内发生的确切时间,你可以用random.random在[0,1]中选取一个浮点数,然后用time.sleep来等待。在

相关问题 更多 >