0

I want to execute an method-call in a variable rate of amount of calls per second. n equals the amount of calls i want to execute in one second. (rather to sleep for seconds, i need to sleep in milliseconds.) I did it this way:

While True:
    method()
    time.sleep(1/n)

Now i would like to know if you know a more elegant and efficient way or is this already good?

TimRicta
  • 135
  • 1
  • 2
  • 8
  • I wouldn't say it's not elegant, it's wrong: imagine that your method takes 0.1 seconds and you want to have it run 10 times a second, then it will just run 5 times, which is wrong. In other programming languages, there are `Timer` classes, which give the opportunity to launch a method every time a certain time limit is reached. I'll advise you to follow such an approach. – Dominique Jul 20 '18 at 08:06

2 Answers2

0

This will e the most efficient way to do it I think as you can assign multiple tasks and create new threads without straining your memory

import threading
n=3
def do_task():
  threading.Timer(1/n, do_task).start()
  print ("done")

do_task()
Inder
  • 3,711
  • 9
  • 27
  • 42
  • But in this case i can't be sure that the processor works off every Thread in the rate i want the command line to be executed. For small rates like `n = 30`calls per second, there could be a queue which the processor can't come after. whereas i use just the `time.sleep`-method there is only one thread i can be sure the processor can run in the rate i want – TimRicta Jul 20 '18 at 09:45
  • Refer here : https://stackoverflow.com/questions/481970/how-many-threads-is-too-many – Inder Jul 20 '18 at 09:53
0

If your method just a separate background task, not have much interact with your other parts of logic, E.g. the task just try to get something from web. Then you may use celery, but if a function inside your program which not so easy to be separated, then bypass my answer.

An example to do a sum function 10 times in one second.

tasks.py

from celery import Celery

app = Celery('tasks',
             broker='redis://localhost',
             backend='redis://localhost')

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    # Calls add(1, 2) every 1/n seconds, here, n=10
    sender.add_periodic_task(0.1, add.s(1, 2), name='add every 1/n seconds')

@app.task
def add(x, y):
    print("running...", x, y)
    return x + y

How to use?

Install redis and celery first.

The in the folder of tasks.py.

In terminal 1 execute: celery -A tasks worker --loglevel=info

In termial 2 execute: celery -A tasks beat --loglevel=info

Then the function add will be run every 0.1 seconds.

atline
  • 28,355
  • 16
  • 77
  • 113