Skip to content Skip to sidebar Skip to footer

Running A Timer For Few Minutes In Python

I am trying to run a certain function 'foo' every second. I have to do this for a few minutes (say 5). The function foo() makes 100 HTTP Requests (which contains a JSON object) to

Solution 1:

I would use another approach which is easier I think.

Create 300 timer thread, each running 1 sec after the previous. The main loop is executed in almost an instant so the error factor is very low. Here's a sample Demo:

import datetime
import thread
import threading

deffoo():
     print datetime.datetime.now()
     print threading.active_count()

for x inrange(0,300): 
     t = threading.Timer(x + 1, foo)
     t.start()

This code output should look like this:

2012-10-01 13:21:07.3280293012012-10-01 13:21:08.3282813002012-10-01 13:21:09.3284492992012-10-01 13:21:10.3286152982012-10-01 13:21:11.3287682972012-10-01 13:21:12.3290062962012-10-01 13:21:13.3292892952012-10-01 13:21:14.3293692942012-10-01 13:21:15.3295802932012-10-01 13:21:16.3297932922012-10-01 13:21:17.3299582912012-10-01 13:21:18.3301382902012-10-01 13:21:19.330300289...

As you can see, each thread is launched about 1 sec after the previous and you are starting exactly 300 threads.

Post a Comment for "Running A Timer For Few Minutes In Python"