Set up a scheduled job?

后端 未结 24 2861
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:13

I\'ve been working on a web app using Django, and I\'m curious if there is a way to schedule a job to run periodically.

Basically I just want to run through the dat

24条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 01:42

    I had exactly the same requirement a while ago, and ended up solving it using APScheduler (User Guide)

    It makes scheduling jobs super simple, and keeps it independent for from request-based execution of some code. Following is a simple example.

    from apscheduler.schedulers.background import BackgroundScheduler
    
    scheduler = BackgroundScheduler()
    job = None
    
    def tick():
        print('One tick!')\
    
    def start_job():
        global job
        job = scheduler.add_job(tick, 'interval', seconds=3600)
        try:
            scheduler.start()
        except:
            pass
    

    Hope this helps somebody!

提交回复
热议问题