If you need to run a function every X minutes/seconds etc. to do some cleanups, trigger some operations you can do a simple scheduler with the help of threading module anddjango custom cli commands.
Let's say I want to invoke a function every 5 seconds to post something on an external API.
In your django app create a folder/package namedmanagement
inside that folder create another folder namedcommands
.In thecommands
folder create a module namedrunposter.py
.In the end you'll have something like this structureyourapp/management/commands/runposter.py
.
In this code we use a thread which runs a while loop as long as it's not stopped every 5 seconds. Replaceprint( "posting" )
with the function/logic you want to run.
# runposter.py
importtime
fromthreadingimportThread,Event
fromdjango.confimportsettings
fromdjango.core.management.baseimportBaseCommand
stop_event=Event()
defmy_job():
whilenotstop_event.is_set():
try:
print("posting")
time.sleep(5)
exceptKeyboardInterrupt:
break
exceptExceptionaserr:
print(err)
continue
classCommand(BaseCommand):
help="Run Poster."
defhandle(self,*args,**options):
poster=Thread(target=my_job)
try:
print("Starting poster...")
poster.start()
whileposter.is_alive():
poster.join(timeout=1)
exceptKeyboardInterrupt:
print("Stopping poster...")
stop_event.set()
poster.join()
print("Poster shut down successfully!")
Nice, now open another terminal window and runPython manage.py runposter
.Command runposter as you can see was created from the module name we've given.
Of course, for something more complex I recommend usingrq-schedulerorcelery periodic tasksordjango-q.
But, for simple cases this should be good enough.