1

I want to make a programme who print "hey" every 5 seconds mine is printing every 5 seconds but more than one time.

import datetime


now = datetime.datetime.today()
objectif = datetime.timedelta(seconds = 50)
later = objectif+now

inc = 0

while later > datetime.datetime.today():
    if datetime.datetime.today().second%5==0 and later.microsecond == datetime.datetime.today().microsecond:
        print "hey"

How can I print "hey" only one time per 5 seconds?

martineau
  • 119,623
  • 25
  • 170
  • 301
Sunrider
  • 25
  • 6
  • An easy way to print every 5 seconds is to use `time.sleep(5)`. Also, you are using python 2.x, consider upgrading to python 3.x. Python 2 is at end-of-life and its best to learn with the new stuff. – tdelaney Mar 03 '20 at 22:59
  • 1
    There are mountains of resources on this topic, both on Stack Overflow and elsewhere. Have you done any research? – AMC Mar 04 '20 at 01:09
  • 1
    Does this answer your question? [What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) – AMC Mar 04 '20 at 01:10

1 Answers1

1

You can use time.sleep()

The following will print 'hey' ever 5 seconds to a limit of 50 seconds

import datetime
from time import sleep

end_time = datetime.datetime.now() + datetime.timedelta(seconds = 50)

while end_time > datetime.datetime.now():
    print("hey")
    sleep(5)
maurera
  • 1,519
  • 1
  • 15
  • 28