Python timer countdown

2019-02-20 00:17发布

I want to know about timer in Python.

Suppose i have a code snippet something like:

def abc()
   print 'Hi'  
   print 'Hello'
   print 'Hai'

And i want to print it every 1 second. Max three times;ie; 1st second i need to check the printf, 2nd second I need to check as well in 3rd second.

In my actual code variables value will be updated. I need to capture at what second all the variables are getting updated.

Can anybody tell me how to do this.

7条回答
贪生不怕死
2楼-- · 2019-02-20 01:00
import time
def abc()
    for i in range(3):
        print 'Hi'  
        print 'Hello'
        print 'Hai'
        time.sleep(1)
查看更多
小情绪 Triste *
3楼-- · 2019-02-20 01:07

time.sleep is fine in this case but what if the abc() function takes half a second to execute? Or 5 minutes? In this case you should use a Timer object.

from threading import Timer

def abc():
    print 'Hi'  
    print 'Hello'
    print 'Hai'

for i in xrange(3):
    Timer(i, abc).start()
查看更多
forever°为你锁心
4楼-- · 2019-02-20 01:08
import time
def abc():
 print 'Hi'
 print 'Hello'
 print 'Hai'

for i in range(3):
 time.sleep(3-i)
 abc()
查看更多
地球回转人心会变
5楼-- · 2019-02-20 01:10

Use time.sleep.

import time

def abc():
    print 'Hi'
    print 'Hello'
    print 'Hai'

for i in xrange(3):
    time.sleep(1)
    abc()   
查看更多
走好不送
6楼-- · 2019-02-20 01:15

You should look into time.sleep(). For example:

for i in xrange(5):
  abc()
  time.sleep(3)

That will print your lines 5 times with a 3 second delay between.

查看更多
太酷不给撩
7楼-- · 2019-02-20 01:17
import sys
import time

c=':'
sec = 0
min = 0
hour = 0

#count up clock

while True:
for y in range(59):                                                 #hours
    for x in range (59):                                            #min
        sec = sec+1
        sec1 = ('%02.f' % sec)                                      #format
        min1 = ('%02.f' % min)
        hour1= ('%02.f' % hour)
        sys.stdout.write('\r'+str(hour1)+c+str(min1)+c+str(sec1))   #clear and write
        time.sleep(1)
    sec = 0
    sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + '00')  #ensure proper timing and display
    time.sleep(1)
    min=min+1
min = 0
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + '00')      #ensure proper timing and display
time.sleep(1)
hour=hour+1
查看更多
登录 后发表回答