How threading.timer works in python [duplicate] - python

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().

Related

Is it possible to cancel an exec() in python after 5 seconds [duplicate]

This question already has answers here:
Timeout on a function call
(23 answers)
Closed 4 months ago.
I am working on a python script that runs small user generated scripts. There is a problem though when a user submits a script that infinitely loops. I was wondering if it would be possible to stop an exec() after 5 seconds of running.
x = exec(user_code)
delay(5)
x.cancel()
something like this ^
So far I tried using threading but the results were mixed. I threaded a function called main which would run their code through exec then I would delete the thread after 5 seconds but it was buggy.
You could use multiprocessing:
import multiprocessing
import time
def exec(n):
for i in range(10000 * n):
print("Whatever") #Your code
if __name__ == '__main__':
process = multiprocessing.Process(target=exec, name="Exec", args=(10,))
process.start()
time.sleep(1) #How much to wait
process.terminate()
process.join()

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)

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

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()

Python Multiprocessing calling object method [duplicate]

This question already has an answer here:
Running multiple threads at the same time
(1 answer)
Closed 5 years ago.
I want to use Python's multiprocessing module to start a new process which creates some other object and calls that objects loops_forever method.
In my main class I have:
import OtherService
from multiprocessing import Process
my_other_service = OtherService(address=ADDRESS)
my_other_process = Process(target=my_other_service.loops_forever())
print("got here")
my_other_process.start()
print("done")
When I run this code, "got here" never gets printed. loops_forever gets called just above the "got here" print, and control never returns back to my main class.
What am I doing wrong here?
I have used multiprocessing before in this fashion:
my_other_process = Process(target=OtherService, kwargs={"address":ADDRESS})
my_other_process.start()
which correctly calls OtherService's init function and runs the init function as a separate process.
The only difference is this time I want to call init function AND then run the loops_forever method forever as a separate process.
When you do target=my_other_service.loops_forever(), you call loops_forever. To pass it as a function, rather than call it, you would drop the parentheses, like target=my_other_service.loops_forever.

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