Reputation: 5578
How can I incremente a number each second? I was thinking to something like this.
import threading
def printit():
second = 1
while threading.Timer(1, printit).start(): #for every second that pass.
print(second)
second += 1
printit()
Upvotes: 1
Views: 1442
Reputation: 373
There are a couple ways of doing this. The first as others have suggested is
import time
def print_second():
second = 0
while True:
second += 1
print(second)
time.sleep(1)
The problem with this method is that it halts execution of the rest of the program (unless it is running in another thread). The other way allows you to perform other processes in the same loop while still incriminating the second counter and printing it out every second.
import time
def print_second_new():
second = 0
last_inc = time.time()
while True:
if time.time() >= last_inc + 1:
second += 1
print(second)
last_inc = time.time()
# <other code to loop through>
Upvotes: 1
Reputation: 12107
I suggest a different method using time.sleep(1)
, the solution would be:
from time import sleep
def printit():
... cpt = 1
... while True:
... print cpt
... sleep(1)
... cpt+=1
time.sleep(secs)
Suspend execution of the current thread for the given number of seconds.
Upvotes: 3