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.