Ryan Jenkins
Ryan Jenkins

Reputation: 890

Delaying execution of code?

I'm sorry if my title is a little unclear. Basically I want to print a '.' every second for five seconds then execute a chunk of code. Here is what I tried:

for iteration in range(5) :
    timer = threading.Timer(1.0, print_dot)
    timer.start()
#Code chunk

It seems as though that Timer starts its own thread for every instance, so the five timers all go off very close to each other plus the code chunk also executes too early.

Upvotes: 0

Views: 131

Answers (2)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59111

Your example queues up 5 timers and starts them all (relatively) at once.

Instead, chain the timers. Pseudo-code (since I hardly know python):

iterationCount = 0
function execute_chained_print_dot:
  if iterationCount < 5
    iterationCount = iterationCount + 1
    timer = threading.Timer(1.0, execute_chained_print_dot)
    timer.start()
  print_dot()
execute_chained_print_dot()

This assumes that the python Timer class only fires the print_dot method once. If it doesn't do this, and repeatedly fires print_dot until it is stopped, then do this instead:

iterationCount = 0
timer = threading.Timer(1.0, execute_print_dot_until_finished)
timer.start()
function execute_print_dot_until_finished:
  if iterationCount < 5
    iterationCount = iterationCount + 1
    print_dot()
  else
    timer.stop()

Disclaimer: I will not be held responsible for any off-by-one errors in this code ;)

Upvotes: 0

Daniel Egeberg
Daniel Egeberg

Reputation: 8382

Use time.sleep().

http://docs.python.org/library/time.html#time.sleep

Upvotes: 3

Related Questions