1

I'm working on a problem where I need to print something every 45 seconds. So I have used time.sleep(45) and made up the code as below:

import timer

def print_data():
   print "Hello World!"
   time.sleep(45)

while True:
   print_data()

I have a couple of queries which I'm trying to understand and learn. I have re-searched this but couldn't get a answer I'm looking for. Please find my queries below:

  1. How do I print the above content continuously exactly for 1 hour waiting every 45 sec?

  2. Can we give a random value say, 30-45 seconds waiting time. So it can wait for any value between 30-45 seconds ?

  3. How does RAM or CPU behave when I put on the timer for 4 -5 hours refreshing/waiting every 60 seconds ? Does this effect the CPU or RAM in any way ?

Kindly help me in understanding these questions. Any help would be appreciated. Thanks in advance.

sdgd
  • 723
  • 1
  • 17
  • 38

2 Answers2

4

This should do what you are looking for:

import time
from random import randint

def print_data():
    print "Hello World!"
    time.sleep(randint(30, 45))

def print_data_for(total_time):
    start_time = time.time()
    while time.time() < start_time + total_time:
        print_data()

print_data_for(60*60)  # 1 hour

As for the CPU/RAM usage, my experience (I have a script based on sleep that prints regular status messages monitoring another process) is that the process is not very expensive at all while it is idling about, which is confirmed here: Python - is time.sleep(n) cpu intensive?

Community
  • 1
  • 1
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

You could print every random value of seconds, and wait for a keyboard interrupt because time.sleep() does nothing.

    import time
    from random import randint 

    def print_data(time, data):
        start_time = time.time()
        if time.time() < start_time + time:
              pass
        except KeyBoardInterrupt:
              data = raw_input("what's your value?")
              print data
        else:
              print data

    data = "Hello World!"

    while True:
          print_data(data)
          if time.time() - start_time > (60*5):
             break
          print "Done!"

Also to know your CPU and RAM usage, you can use the psutil library https://pypi.python.org/pypi/psutil, psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.

It currently supports Linux, OS X, FreeBSD and Windows with Python versions from 2.4 to 3.1 by using a unique code base.

opeonikute
  • 494
  • 1
  • 4
  • 15