Executing Specific Statement At A Given Rate In Python
I want to write a code which execute a statement specified number of times per second, Many of you might be familier about the term rate Here i want rate to be 30 per second say i
Solution 1:
The sched
module is intended for exactly this:
from __future__ import division
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
defschedule_it(frequency, duration, callable, *args):
no_of_events = int( duration / frequency )
priority = 1# not used, lets you assign execution order to events scheduled for the same timefor i in xrange( no_of_events ):
delay = i * frequency
scheduler.enter( delay, priority, callable, args)
defprinter(x):
print x
# execute printer 30 times a second for 60 seconds
schedule_it(1/30, 60, printer, 'hello')
scheduler.run()
For a threaded environment, the use of sched.scheduler
can be replaced by threading.Timer
:
from __future__ import division
import time
import threading
defschedule_it(frequency, duration, callable, *args, **kwargs):
no_of_events = int( duration / frequency )
for i in xrange( no_of_events ):
delay = i * frequency
threading.Timer(delay, callable, args=args, kwargs=kwargs).start()
defprinter(x):
print x
schedule_it(5, 10, printer, 'hello')
Solution 2:
Try using threading.Timer
:
def hello():
print "hello, world"
t =Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
Solution 3:
You can use time.time()
to do what you want:
import time
defyour_function():
# do something...whileTrue:
start = time.time() # gives current time in seconds since Jan 1, 1970 (in Unix)
your_function()
whileTrue:
current_time = time.time()
if current_time - start >= 1.0/30.0:
break
This will make sure that the delay between calls of your_function
is very close to 1/30 of a second, even if your_function
takes some time to run.
There is another way: using Pythons built-in scheduling module, sched
. I never used it, so I can't help you there, but have a look at it.
Solution 4:
After some time spending i discovered how to do it well i used multiprocessing in python to achieve it here's my solution
#!/usr/bin/env pythonfrom multiprocessing import Process
import os
import time
import datetime
defsleeper(name, seconds):
time.sleep(seconds)
print"PNAME:- %s"%name
if __name__ == '__main__':
pros={}
processes=[]
i=0
time2=0
time1=datetime.datetime.now()
for sec inrange(5):
flag=0while flag!=1:
time2=datetime.datetime.now()
if (time2-time1).seconds==1:
time1=time2
flag=1print"Executing Per second"for no inrange(5):
i+=1
pros[i] = Process(target=sleeper, args=("Thread-%d"%i, 1))
j=i-5for no inrange(5):
j+=1
pros[j].start()
j=i-5for no inrange(5):
j+=1
processes.append(pros[j])
for p in processes:
p.join()
Post a Comment for "Executing Specific Statement At A Given Rate In Python"