-2

I want to make a function that prints a statement every 2 minutes. I'm really new to Python and don't fully understand the time library. This is the code I have so far:

 from datetime import datetime
 import time                

 now = datetime.now()       

 print now.second           
 print "start"
   while True:
      print "while loop started"
    if (now % 2 == 0):     
       print "Hello"     
    else:                  
       break 

How can I do this?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Ari K.
  • 11
  • 2

2 Answers2

5

You can use time.sleep here. Since you want a timer for 2 minutes, pass 120 (seconds) as the argument value.

Basically, this translates into something like below:

while True:
    time.sleep(120)
    print "Hello"     

This will print "Hello" every 2 minutes.

Note that time.sleep is not entirely accurate, and may be off by a small but arbitrary amount of time because of OS scheduling of other processes etc and execution of the code itself.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
2

Use the sched module

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print "Doing stuff..."
    # do your stuff
    sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

take a look here.

Community
  • 1
  • 1