'How do I run a loop in Django while server is working as usual?
I am trying to create a csgo trading website where the users can withdraw and deposit skins. To do so I have created a bot account that sends trading offers to the customer. Now I need to somehow confirm that the trade was accepted by the user. I am new to this so there might be a better, simple solution that I just can't figure out. I am using steampy library.
What I think would be the solution is to run a function loop that checks for the offers and their state. And on state change would update the database. But I do not know how I can create a function like this in Django so the server would also be running at the same time. I want to also use this project in production so running a script from my computer isn't the solution.
Can someone please help me with the issue or lead me in the right direction?
Solution 1:[1]
Based on SimbaOG's answer, I did the following steps which worked fine for me:
initialize scheduler
created alerts_check.py
from apscheduler.schedulers.background import BackgroundScheduler
# added schedule, ensure its only done once
def alerts_schedule():
scheduler = BackgroundScheduler()
if not scheduler.get_job('alert_check_job'):
scheduler.add_job(alerts_check, 'interval', seconds=30, id='alert_check_job')
scheduler.start()
def alerts_check():
# somewhere init log with logging.getLogger(__name__)
log.info("****** checking for alerts...")
Invoke the alerts_check function from django startup
In apps.py
from django.apps import AppConfig as DjangoAppConfig
import logging
import sys, os
log = logging.getLogger(__name__)
class AppConfig(DjangoAppConfig):
name = "app"
def ready(self):
# use an environment variable to run once only
# check for 'runserver' so migrate etc is avoided
once_key = 'CMD_RUN_ONCE'
run_once = os.environ.get(once_key)
if run_once is not None or 'runserver' not in sys.argv:
return True
os.environ[once_key] = 'True'
# import is done only here after models are loaded
from app.alerts_check import alerts_schedule
alerts_schedule()
log.info(f"Service has started...............")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | msanjay |
