Cancel timer in Python - python

I am working on timer class in python and wrote a simple test code for the same. My purpose is to print the "hello world" message 10 times and then cancel the timer once the iterations are done. The problem is I am unable to cancel the timer and code seems to print "hello world" infinitely.
Below is my code:
from threading import Timer
class myclass():
iteration_count = 0
heartbeat = 1
def printMsg(self):
print "hello world!"
def start_job(self):
self.printMsg()
self.iteration_count = self.iteration_count + 1
if self.iteration_count == 10:
Timer(self.heartbeat, self.start_job, ()).cancel()
Timer(self.heartbeat, self.start_job, ()).start()
m = myclass()
m.start_job()
I am using Python 2.7
Any help would be highly appreciated

Your problem is you've made another Timer() in if condition and .cancel() it. The following code solves your problem:
from threading import Timer
class MyClass(object):
def __init__(self):
self.iteration_count = 0
self.heartbeat = 1
#staticmethod
def print_msg():
print "hello world!"
def start_job(self):
self.print_msg()
self.iteration_count += 1
timer = Timer(
interval=self.heartbeat,
function=self.start_job,
)
timer.start()
if self.iteration_count >= 10:
timer.cancel()
MyClass().start_job()

Seems like you start your timer again right after you cancelled it.
If you change your code to return from start_job() when your end-condition is reached it should work.
if self.iteration_count == 10:
Timer(self.heartbeat, self.start_job, ()).cancel()
return
Actually you don't even have to cancel the timer this way, you just don't start a new one, if the condition is reached.

cancelmethod is used to stop the created timer before its action has begun, so just return will be ok.
if self.iteration_count == 10:
return
See Timer Objects
The timer can be stopped (before its action has begun) by calling the cancel() method.
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # will print "hello, world" after 30 seconds
t.cancel() # stop it printing "hello, world"

Related

Print message while a function is running in Python with AsyncIO

I'm trying to create a print function that keeps printing, for example, 'Hello World', while another function (called miner) is running in parallel, and both functions must end at the same time.
This is for a real-time cost measurer for bitcoin mining that I'm working on.
I found that python as asyncio and tried to use it, however I couldn't get the print function to stop at the same time the miner function ends. The timer function printed once and waited for the miner function.
import asyncio
import time
from datetime import datetime
class Test2:
async def miner(self):
await asyncio.sleep(5)
return 0
async def timer(self):
while True:
print("\n Hello World \n")
time.sleep(1)
t2 = Test2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(t2.miner(), t2.timer()))
I tried concurrent tasks, but both function does not run in parallel (timer and miner).
Could you show me a way to solve this?
Thank you!
time.sleep() is not asynchronous function so timer process locks other operations before it ends (but unfortunately it is endless)
You may add shared trigger variable to stop timer when miner complete
import asyncio
class Test2:
is_ended = False
async def miner(self):
await asyncio.sleep(5)
self.is_ended = True
print("\n I'm done \n")
return 0
async def timer(self):
while True:
if self.is_ended:
print('\n Bye Bye \n')
break
print("\n Hello World \n")
await asyncio.sleep(1)
t2 = Test2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(t2.miner(), t2.timer()))
Hello World
Hello World
Hello World
Hello World
Hello World
I'm done
Bye Bye
You can also use threading:-
def func1():
print('Working')
def func2():
print("Working")
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
You can use multiprocessing or threading
from multiprocessing import Process
index=0
def func1():
global index
print ('start func1')
while index< 20:
index+= 1
print ('end func1')
def func2():
global rocket
print ('start func2')
while index< 10:
index+= 1
print ('end func2')
if __name__=='__main__':
p1 = Process(target = func1)
p1.start()
p2 = Process(target = func2)
p2.start()
for treading
import threading
x = threading.Thread(target=func1)
y = threading.Thread(target=func1)

Python Thread counter

I'm trying to make thread counter but I'm stuck. I've got the code below:
import threading
def Hello():
global t
print("Hello!")
t = threading.Timer(1, Hello)
t.start()
Hello()
How can I make the loop stop say after 5 'Hellos'?
Not sure what you're trying to accomplish but this code will work
import threading
count = 0
def hello():
global count
print("Hello!")
count += 1
if count < 5:
t = threading.Timer(1, function=hello,)
t.start()
hello()

How to cancel a setInterval in python?

I am using this code to call a function doSomething every 3 seconds. but I want that when numeroPeticiones== 3, stop doing it. I have looked for many examples, but none works. In my case, my function continues to be executed eternally, even though the condition of numeroPeticiones== 3 is fulfilled. how can I solve that?
import threading
from threading import Timer
numeroPeticiones=0
def doSomething():
global numeroPeticiones
numeroPeticiones=numeroPeticiones+1
print ("hello, world",numeroPeticiones)
if numeroPeticiones == 3:
print("cancel")
t.cancel()
def set_interval(func, sec):
def func_wrapper():
set_interval(func, sec)
func()
t = threading.Timer(sec, func_wrapper)
t.start()
return t
You can do the following, if num is equal to the 3, it wont start the timer
from threading import Timer
num = 0
def hello():
global num
num += 1
print("hello, world")
if (num < 3):
Timer(3, hello).start()
Timer(3, hello).start()

How to set up the thread.Timer without a function?

I am working on my code to set up the timer. I want to set up the Timer without creating the function.
Here is what I use:
def hello(self):
print "hello, world"
self.getControl(MyPlayer.Control_EPG_ID).setVisible(False)
def onAction(self, action):
if action.getId() == ACTION_MOVE_DOWN:
t = threading.Timer(5.0, self.hello)
t.start()
I want to make it to show something is like this:
t = threading.Timer(5.0)
t.start()
self.getControl(MyPlayer.Control_EPG_ID).setVisible(False)
when I try it, it give me an error. Do you know how I can set up the timer without create a function? if so how?
You should be able to nest hello() inside of onAction() like this. It will use the self argument passed to the outer function:
def onAction(self, action):
def hello():
print "hello, world"
self.getControl(MyPlayer.Control_EPG_ID).setVisible(False)
if action.getId() == ACTION_MOVE_DOWN:
t = threading.Timer(5.0, hello)
t.start()
Why not like this:
import time
time.sleep(5) # delays for 5 seconds

Implementing Timeout. Whats wrong with the following code?

The program prints Expired the first time. I am expecting the code to print "not expired" for atleast 4 times before printing expired. Can someone please explain the reason and help me correct the code. Thank you
import time
TIMEOUT = 5
class Timer ():
def __init__(self):
self.timeout = time.time()+TIMEOUT
def isExpired ():
return time.time() > self.timeout
timing = Timer()
def main():
while 1:
if timing.isExpired:
print "Expired"
return
else:
print "Not expired"
print "sleeping for 1 second"
time.sleep(1)
if __name__== "__main__":
main()
You have several problems:
You did not give your isExpired method a self argument. Define it as def isExpired(self):.
You are creating a new Timer instance on each loop iteration. Move the timing = Timer() outside the while loop.
timing.isExpired is a reference to the method object iself (which is always true in a boolean context). You need to do timing.isExpired() to actually call it.
These are all basic Python issues that have nothing to do with Timer. Read the Python tutorial to learn how to use classes and so on.
You are creating a Timer instance everytime. Take it away from loop, or your while loop is never going to terminate. Also, you need to call timing.isExpired as it is a method. So your code should be:
import time
TIMEOUT = 60 * 5
class Timer ():
def __init__(self):
self.timeout = time.time()+TIMEOUT
def isExpired (self):
return time.time() > self.timeout
def main():
timing = Timer()
while 1:
if timing.isExpired():
print "Expired"
return
else:
print "Not expired"
print "sleeping for 1 second"
time.sleep(1)

Categories

Resources