Using sleep() to create a function that consistently loops every second [duplicate] - python

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 4 years ago.
I have a program that needs to execute every second. However I am concerned that the code would add a slight delay in turn causing it delay slightly longer then intended. Sample code:
while True:
print(time)
sleep(1)
In my case I will be adding more complicated function calls in this loop and am concerned that they will mess with my timer. Should I even be worried, and or is there another way for me to ensure this function loops every second?

You can use this:
import threading
def scheduleFunc():
threading.Timer(1.0, scheduleFunc).start()
print(time)
Or use this:
import sched, time
scheduled = sched.scheduler(time.time, time.sleep)
def scheduleFunc(sc):
print(time)
scheduled.enter(60, 1, scheduleFunc, (sc,))
scheduled.enter(60, 1, scheduleFunc, (scheduled,))
scheduled.run()

Related

A general programming question: Is there a way to trigger a function every x seconds without remembering the last time it was triggered? [duplicate]

This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed last month.
Sorry if this is a basic question, but I want to have a function trigger every fixed amount of time, say 2 seconds. In general I would do something like:
lifetime = getCurrentTime
if (lifetime - lastTime > triggerTime)
doTheThing()
lastTime = lifetime
end
This normally works fine, but I'm working on a program where each object stores its own lifetime, and there could be hundreds of objects at once. I'm wondering if there's a way that each object wouldn't need to also remember its own lastTime -- I was thinking something with rounding or modulo, but even then you'd still need to remember how many times the function had triggered before.
I'm wondering if anyone knows of a good general way to have a trigger function every x seconds without having to remember the last time it triggered or how many times it's triggered?
Have you tried using sched yet? Here's a task done every 5 seconds to get you started:
import sched
import time
def doTheThing(runnable_task, every):
runnable_task.enter(every, 1, doTheThing, (runnable_task, every))
print("The thing...")
task = sched.scheduler(time.time, time.sleep)
every = 5
task.enter(every, 1, doTheThing, (task, every))
task.run()

How can I run my code at a specific time? [duplicate]

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)

Python while loop be executed in time interval [duplicate]

This question already has answers here:
How do I make a time delay? [duplicate]
(13 answers)
Closed 2 years ago.
I wanted to use while loop to keep executing my script over and over but there is a problem as my code calls an API that doesn't allow so many calls in small time so I wanted to make the while loop be executed at time interval so I tried this code
from threading import Timer
def myfunc():
some code
while True:
t = Timer(1.0, myfunc)
t.start()
but it doesn't work, so is there any other way to do it correctly?
Use the time module:
import time
def myfunc():
some code
while True:
myfunc()
# unit is in second. Example below wait for 1 second before continuing
time.sleep(1)

How threading.timer works in python [duplicate]

This question already has answers here:
How Python threading Timer work internally?
(2 answers)
Closed 5 months ago.
I want to run a function every n seconds. After some research, I figured out this code:
import threading
def print_hello():
threading.Timer(5.0, print_hello).start()
print("hello")
print_hello()
Will a new thread be created every 5 sec when print_hello() is called?
Timer is a thread. Its created when you instantiate Timer(). That thread waits the given amount of time then calls the function. Since the function creates a new timer, yes, it is called every 5 seconds.
Little indentation of code would help to better understand the question.
Formatted Code:
from threading import Timer
def print_hello():
Timer(5.0,print_hello,[]).start()
print "Hello"
print_hello()
This code works spawning a new thread every 5 sec as you are calling it recursively in every new thread call.
In my case this worked
import turtle
def hello:
threading.Timer(2, hello()).start()
hello()
hello function should contain braces while passing as an argument in Timer().

How to repeat a function every N minutes? [duplicate]

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 7 years ago.
In my python script I want to repeat a function every N minutes, and, of course, the main thread has to keep working as well. In the main thread I have this:
# something
# ......
while True:
# something else
sleep(1)
So how can I create a function (I guess, in another thread) which executes every N minutes? Should I use a timer, or Even, or just a Thread? I'm a bit confused.
use a thread
import threading
def hello_world():
threading.Timer(60.0, hello_world).start() # called every minute
print("Hello, World!")
hello_world()

Categories