No function call delay

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

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

but when looking at the log, I see that the postit function does not delay at all, and it just makes all the timer calls to post them almost instantly.

So, how to really randomly delay any function call without using timer.sleep since it hangs from the application.

When viewing the log following timestamps, the log is logged inside the posit function, BEGIN is the beginning 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

Sample code:

def startsession():
with session() as c:'...', data=payloadlogin,headers = headers)'...',data=payloaddata,headers = headers)

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

        e=(code,part, pics,rep)

        if rep!='':
            def postreply(replydata):
      '...',data=replydata,headers = headers)
       +" "+str(represponse))

            threading.Timer(int(random.random()*20), postreply,[replydata]).start()
            print i+replydata['pos']

if __name__ == '__main__':



source to share

1 answer

According to the Timer


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


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

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


Now postit

- this is the function to be called, and [data]

- these are the arguments to be passed to the function postit

when called.

You can also use a tuple as arguments, for example

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




All Articles