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

      

+3


source to share


1 answer


According to the Timer

definition

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

      

+2


source







All Articles