Use of the random function to randomise scheduled tasks

丶灬走出姿态 提交于 2019-12-11 11:21:58

问题


I am trying to use the code:

import random
import datetime
from sched import scheduler
from time import time, sleep

s = scheduler(time, sleep)
random.seed()

def run_periodically(start, end, interval, func):
    event_time = start
    while event_time < end:
        s.enterabs(event_time, 0, func, ())
        event_time += interval + random.random(-5, 45)
    s.run()

getData()#######

run_periodically(time()+5, time()+1000000, 10, getData)

I am trying to get the scheduled time and or the scheduled interval to have some degree of randomisation, currently the code returns the

typeError: random() takes no arguments (2 given)

If anyone could either tell me how to fix this or provide an alternative method it would be greatly appreciated.


回答1:


Type help(random.random) in the terminal (or random.random?? if you're using iPython) and you'll get:

random() -> x in the interval [0, 1).

So it doesn't take any input which is the reason behind the error. To generate a random number within a certain range you can use random.randint (which is linked to random.randrange).

So it would be like this for your case: random.randint(-5,45)




回答2:


random.random is not the function you want. You want to use random.randrange or random.randint depending on your version.

See http://docs.python.org/2/library/random.html for more details.



来源:https://stackoverflow.com/questions/16930228/use-of-the-random-function-to-randomise-scheduled-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!