简体   繁体   中英

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?

the solution for your problem would be to use BackgroundSchedulers and/or Cron jobs. These work in the background and won't affect your django server so you can server files and data as usual.

I personally use APScheduler for my django application to scheduler background tasks, it is an amazing module but requires some documentation. It has different types of task scheduler so you can try them.

APScheduler Guide

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...............")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM