stackit
stackit

Reputation: 3106

No delay in function call

For a random delayed execution of a function i used following code in a for loop with index i decreasing for each iteration and randomtime is an array of random values:

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

but on examining the log I see that postit function is not delayed at all and it just executes all timer calls to postit almost instantly.

So how to really randomly delay each function call without using timer.sleep as it freezes the app.

On seeing the log following arbitary order timestamps are seen, the logging is done inside posit function, BEGIN is the start of the program:

2015-04-24 19:06:20,775 INFO 
2015-04-24 19:06:20,782 INFO
2015-04-24 19:06:21,749 INFO 
.
:
2015-04-24 19:06:25,845 INFO BEGIN

Code sample:

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()

Upvotes: 3

Views: 114

Answers (1)

thefourtheye
thefourtheye

Reputation: 239463

As per the Timer's definition

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

you need to pass the function object as the second parameter and a list of arguments to be passed to the function. So, you need to write it like this

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

Now, postit is the function to be called and [data] is the arguments to be passed to the postit function when invoked.

You can also use a tuple as arguments, like this

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

Upvotes: 2

Related Questions