This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 6 years ago.
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:
How do I print the above content continuously exactly for 1 hour waiting every 45 sec?
Can we give a random value say, 30-45 seconds waiting time. So it can wait for any value between 30-45 seconds ?
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.
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?
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.
Related
This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed 1 year ago.
I am developing a software with python. And I want my code to run at certain hours. It will run once every 5 minutes without a break. But I want it to work exactly at certain hours and minutes. For example, such as 20:00, 20:05, 20:10...
I used time.sleep(300) but if for example 5 seconds passes after my program runs, it starts to delay 5 seconds in each run and for example it starts running 1 minute late after 12 runs. For example, it should work at 20:05, but it starts at 20:06.
How can I provide this?
You can use schedule module
import schedule
import time
from datetime import datetime
now = datetime.now()
def omghi():
print("omg hi there xD")
schedule.every(5).minutes.do(omghi)
while True:
schedule.run_pending()
time.sleep(1)
There is a useful model for that case.
It is an external model, you have to download it using pip and it is called
schedule
https://pypi.org/project/schedule/ - here you can see all the details.
I believe that using timed threads works the best with what you want. This excellent answer uses threading.Timer from the library threading as follows:
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
Thank you very much for the answers. But this is how I handled it and I wanted to share it with you :)
import time
from datetime import datetime
while True:
now = datetime.now()
if (now.minute % 5) == 0 and now.second == 0:
print("Fire!")
time.sleep(1)
I am trying to create a scheduled task in Python using Win32com. I am able to create a daily trigger. However, I cannot find a way to create a trigger every 5 seconds or every minute for that matter. Does anybody have any pointers on how to do that?
As said in a comment, if you want to do stuff with this frequency you are better off just having your program run forever and do its own scheduling.
In a similar fashion to #Barmak Shemirani's answer, but without spawning threads:
import time
def screenshot():
# do your screenshot...
interval = 5.
target_time = time.monotonic() + interval
while True:
screenshot()
delay = target_time - time.monotonic()
if delay > 0.:
time.sleep(delay)
target_time += interval
or, if your screenshot is fast enough and you don't really care about precise timing:
while True:
screenshot()
time.sleep(interval)
If you want this to run from the system startup, you'll have to make it a service, and change the exit condition accordingly.
pywin32 is not required to create schedule or timer. Use the following:
import threading
def screenshot():
#pywin32 code here
print ("Test")
def starttimer():
threading.Timer(1.0, starttimer).start()
screenshot()
starttimer()
Use pywin32 for taking screenshot etc.
I am making a Who Wants to be a Millionare game in Python using graphics. I want the user to get 45 seconds per question to answer it. However, whenever I put a timer in my code it waits for 45 seconds first, then lets the user answer, instead of running in the background and letting the user answer at the same time.
Using the threading module to run multiple threads at once
You could use the Python threading module to make two things happen at once, thereby allowing the user to answer while the timer ticks down.
Some example code utilizing this:
from threading import Thread
from time import sleep
import sys
def timer():
for i in range(45):
sleep(1) #waits 45 seconds
sys.exit() #stops program after timer runs out, you could also have it print something or keep the user from attempting to answer any longer
def question():
answer = input("foo?")
t1 = Thread(target=timer)
t2 = Thread(target=question)
t1.start() #Calls first function
t2.start() #Calls second function to run at same time
It's not perfect, but this code should start two different threads, one asking a question and one timing out 45 seconds before terminating the program. More information on threading can be found in the docs. Hope this helps with your project!
Try using time.time(). This returns a the amount of seconds since January 1, 1970 in UNIXTime. You can then create a while loop such that:
initial_time = time.time()
while time.time()-initial_time < 45:
#Code
Hope this helped!
I have a multi-threaded SMTP server. Each thread takes care of one client. I need to set a timeout value of 10 seconds on each server thread to terminate dormant or misbehaving clients.
I have used the time.time(), to find the start time and my checkpoint time and the difference gives the running time. But I believe it gives the system time and not the time this thread was running.
Is there a Thread local timer API in Python ?
import threading
stop = 0
def hello():
stop = 1
t=threading.Timer(10,hello)
t.start()
while stop != 1:
print stop
print "stop changed"
This prints 0 (initial stop) in a loop and does not come out of the while loop.
Python has progressed in the 6 years since this question was asked, and in version 3.3 it's introduced a tool for exactly what was being asked for here:
time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID)
Python 3.7 additionally introduced an analogous time.clock_gettime_ns.
Detailed docs are exactly where you'd expect but the feature is pretty straightforward straight out of the box.
In the python documentation there is no mention of "thread timing". Either the clocks are process-wide or system-wide. In particular time.clock measures process time while time.time returns the system time.
In python3.3 the timings API was revised and improved but still, I can't see any timer that would return the process time taken by a single thread.
Also note that even if possible it's not at all easy to write such a timer.
Timers are OS specific, so you would have to write a different version of the module for every OS. If you want to profile a specific action, just launch it without threads.
When threaded the timing either it runs as expected, or it is a lot slower because of the OS, in which case you can't do nothing about it(at least, if you don't want to write a patch that "fixes" the GIL or removes it safely).
Python 3.7 has added the time.thread_time() method that seems to do what this question needs. According to the docs, it is thread-specific and excludes time spent sleeping.
The hello function's stop value is local, not the global one.
Add the following:
def hello():
global stop
stop = 1
I am posting a sample code which can measure the running time of the thread, you can modify the code, so as to use with your function.
import time
import threading
def hello():
x = 0
while x < 100000000:
pass
x += 1
start = time.clock()
t = threading.Thread(target = hello, args = ())
t.start()
t.join()
end = time.clock()
print "The time was {}".format(end - start)
On my system, it gave a time of 8.34 seconds.
I have written a scraper that does html scraping and then use API to get some data, since its a very lengthy code I haven't put it here. I have implemented random sleep method and using it within my code to monitor throttle. But I want to make sure I don't over run this code, so my idea is to run for an 3-4 hours then taker breather and then run again. I haven't done anything like this in python I was trying to search but not really sure where to start from, it would be great if I get some guidance on this. If python has a specific module link to that would be a great help.
Also is this relevant? I don't I need this level of complication?
Suggestions for a Cron like scheduler in Python?
I have functions for every single scraping task, and I have main method calling all those functions.
You can use a threading.Timer object to schedule an interrupt signal to the main thread after the time is exceeded:
import thread, threading
def longjob():
try:
# do your job
while True:
print '*',
except KeyboardInterrupt:
# do your cleanup
print 'ok, giving up'
def terminate():
print 'sorry, pal'
thread.interrupt_main()
time_limit = 5 # terminate in 5 seconds
threading.Timer(time_limit, terminate).start()
longjob()
Put this in your crontab and run every time_limit + 2 minutes.
You could just note the time you have started and each time you want to run something make sure you haven't exceeded the given maximum. Something like this should get you started:
from datetime import datetime
MAX_SECONDS = 3600
# note the time you have started
start = datetime.now()
while True:
current = datetime.now()
diff = current-start
if diff.seconds >= MAX_SECONDS:
# break the loop after MAX_SECONDS
break
# MAX_SECONDS not exceeded, run more tasks
scrape_some_more()
Here's the link to the datetime module documentation.