Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
While循环中的Python随机_Python_Python 2.7_Python 3.x - Fatal编程技术网

While循环中的Python随机

While循环中的Python随机,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我有一个基本上在while循环中执行的Python脚本: 而1: 我想做的是让它随机执行一个动作,比如,每小时一次或两次 我尝试过像if random.random()>5:这样的解决方案,但这种情况太频繁了 你知道我如何确保它每小时响一两次,而不经常响吗?使用随机化器为动作创建运行时间。这不会阻止循环中的其他操作 import time import random def get_new_time_to_perform_action(): delay_minutes = (30 + r

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

而1:
我想做的是让它随机执行一个动作,比如,每小时一次或两次

我尝试过像if random.random()>5:这样的解决方案,但这种情况太频繁了


你知道我如何确保它每小时响一两次,而不经常响吗?

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

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>
导入时间
随机输入
def获取新的执行操作的时间()
延迟分钟=(30+random.random()*30)#30-60分钟
返回时间。time()+延迟分钟*60
下一次运行=获取新的执行操作的时间()
尽管如此:
如果(time.time()>=下次运行时间):
# 
下一次运行=获取新的执行操作的时间()
# 

如果您有一个时间窗口,那么应用睡眠间隔可能是一个不错的选择

通过示例,您可以执行以下操作:

from time import sleep
from random import randint

while 1:
  <do stuff>
  sleep(randint(0, 3600))
从时间导入睡眠
从随机导入randint
而1:
睡眠(randint(03600))

为了控制每小时的重复次数,我建议用
随机选择一个int。randint
然后选择事件在一小时内发生的确切时刻,您可以在[0,1]中选择一个浮点[使用
random.random
并将其转换为秒数,然后等待
时间。sleep

为什么不选择0和59之间的两个随机数并执行(一次)当小时后的分钟数达到该值时。然后在这两个值都达到后,重做。@downshift在我看来,周期性与随机性是相反的……我不能使用睡眠,因为我需要应用程序的其余部分仍在运行。在这种情况下,如果您与程序的其他部分有一些共享资源,则此代码段可以在另一个线程上运行。我如果没有共享资源,您可以考虑将此块提取到一个单独的python脚本中,并在crontab上进行调度。您不需要crontab来防止阻塞。只需选择一个随机运行的时间。我更新了我的代码片段作为示例。我只是建议将cronjobs作为一种分离代码块的方法,并考虑函数的独立性nalities和异步运行时。只需一行crontab,就可以简化有关同步和共享资源的许多问题。我认为这是最佳答案。您可以使用
np.random.normal(avg\u wait,std\u wait)
而不是
random.random()
为了获得更多的控制并能够分别更改等待时间的平均值和标准偏差。将所有任务放在与独立任务的特定规则耦合的循环中似乎不是一个好的工程决策。是的,这就是我所做的。