duck
duck

Reputation: 2561

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 want to execute a function 30 times per second for 60 seconds means rate=30/sec duration=60sec

Can any one tell me is their any api available in python to do the same ?

Upvotes: 5

Views: 3320

Answers (4)

Matthew Trevor
Matthew Trevor

Reputation: 14962

The sched module is intended for exactly this:

from __future__ import division
import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def schedule_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 time
    for i in xrange( no_of_events ):
        delay = i * frequency
        scheduler.enter( delay, priority, callable, args)

def printer(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

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

def printer(x):
    print x

schedule_it(5, 10, printer, 'hello')

Upvotes: 2

duck
duck

Reputation: 2561

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 python
from multiprocessing import Process
import os
import time
import datetime
def sleeper(name, seconds):
   time.sleep(seconds)
   print "PNAME:- %s"%name


if __name__ == '__main__':
   pros={}
   processes=[]
   i=0
   time2=0
   time1=datetime.datetime.now()
   for sec in range(5):
        flag=0
        while flag!=1:
                time2=datetime.datetime.now()
                if (time2-time1).seconds==1:
                        time1=time2
                        flag=1
                        print "Executing Per second"
                        for no in range(5):
                                i+=1
                                pros[i] = Process(target=sleeper, args=("Thread-%d"%i, 1))
                        j=i-5
                        for no in range(5):
                                j+=1
                                pros[j].start()
                        j=i-5
                        for no in range(5):
                                j+=1
                                processes.append(pros[j])
   for p in processes:
        p.join()

Upvotes: -1

HerrKaputt
HerrKaputt

Reputation: 2604

You can use time.time() to do what you want:

import time

def your_function():
    # do something...

while True:
    start = time.time() # gives current time in seconds since Jan 1, 1970 (in Unix)
    your_function()
    while True:
        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.

Upvotes: 0

warvariuc
warvariuc

Reputation: 59604

Try using threading.Timer:

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

Upvotes: 0

Related Questions