While 循环中的 Python 随机数

标签 python python-2.7 python-3.x

<分区>

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

while 1:
  <do stuff>

我想做的是让它随机执行一个 Action ,比如每小时一次或两次。

我已经尝试过像 if random.random() > 5: 这样的解决方案,但它发生得太频繁了。

有什么想法可以确保它每小时熄灭一次或两次,而不是一直熄灭吗?

最佳答案

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

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>

关于While 循环中的 Python 随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41007087/

相关文章:

python - 如何格式化最多 N 位小数的数字,其中 N 是随机的

python - South 无法创建新字段,因为字段不存在

python - 在 PySpark 中转置 RowMatrix

python - Python中有一个函数可以列出特定对象的属性和方法吗?

python - 'builtin_function_or_method' 列出

python - 使用 python 在并发.futures 中 as_completed 出现意外行为。

python - 如何在plotly中制作countplot

python - 如何以 ?(a*p+b)/p**2 的形式提取字符串的 a,b 的值

mysql - Makemigrations值错误: too many values to unpack

python - Beautiful Soup 将 Unicode 字符转换为 HTML 实体