【问题标题】:No delay in function call函数调用无延迟
【发布时间】:2015-04-24 06:36:13
【问题描述】:

对于函数的随机延迟执行,我在 for 循环中使用了以下代码,每次迭代时索引 i 递减,randomtime 是一个随机值数组:

threading.Timer(int(random.random()*20)+i, postit,[replydata]).start()

但在检查日志时,我发现 postit 函数根本没有延迟,它几乎立即执行所有对 postit 的计时器调用。

那么如何在不使用 timer.sleep 的情况下真正随机延迟每个函数调用,因为它会冻结应用程序。

在看到以下任意顺序时间戳的日志时,日志记录是在 posit 函数中完成的,BEGIN 是程序的开始:

2015-04-24 19:06:20,775 信息 2015-04-24 19:06:20,782 信息 2015-04-24 19:06:21,749 信息 . : 2015-04-24 19:06:25,845 信息开始

代码示例:

def startsession():
with session() as c:
    preq=c.post('...', data=payloadlogin,headers = headers)
    response=c.post('...',data=payloaddata,headers = headers)
    j=json.loads(response.text)
    logger.info('BEGIN'+str(c.cookies.items()))

    #print j
    for i in range(len(j['data'])-1,0,-1) :
        part=j['data'][i]['body']
        code=j['data'][i]['code']
        pics=''
        for t in range(len(j['data'][i]['pics'])):
            pics=pics+j['data'][i]['pics'][t]['name']+' , '


        rep=getreply(part,pics)
        e=(code,part, pics,rep)


        if rep!='':
            replydata['cod']=code
            replydata['rep']=rep
            replydata['pos']=int(random.random()*10)
            def postreply(replydata):
                represponse=c.post('...',data=replydata,headers = headers)
                logger.info(str(e) +" "+str(represponse))


            threading.Timer(int(random.random()*20), postreply,[replydata]).start()
            print i+replydata['pos']
        else:
            logger.info(str(e))

if __name__ == '__main__':
    startsession()

【问题讨论】:

  • it just executes all of them when called. - 这是什么意思?
  • 所有函数调用一次执行,没有看到延迟,@thefourtheye

标签: python multithreading python-2.7 logging random


【解决方案1】:

根据Timer's definition

threading.Timer(interval, function, args=[], kwargs={})

您需要将函数对象作为第二个参数和要传递给函数的参数列表传递。所以,你需要这样写

threading.Timer(int(random.random()*10)+i, postit, [data]).start()

现在,postit 是要调用的函数,[data] 是要在调用时传递给 postit 函数的参数。

你也可以使用元组作为参数,像这样

threading.Timer(int(random.random()*10)+i, postit, (data,)).start()

【讨论】:

  • 是的,但这并不能解决问题,所有调用仍然立即执行
  • @stackit 你能发布一个可重复的样本吗?还有您尝试过的实际代码。
  • 代码在for循环中运行,因此每次都会触发计时器。
  • 我可以确认 thefourtheye 的实现在一个简单的循环中按预期工作,您的代码中肯定有其他内容。
  • 延迟时间大约为 7、2、6、8 秒,而程序仅在 2-3 秒内运行并结束!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多