我需要在Django应用程序中实现计划任务 . DBader的schedule似乎是这项工作的一个很好的候选者,但是当它作为Django项目的一部分运行时,它似乎没有产生预期的效果 .
具体来说,这作为一个独立的程序很好:
import schedule
import time
import logging
log = logging.getLogger(__name__)
def handleAnnotationsWithoutRequests(settings):
'''
From settings passed in, grab job-ids list
For each job-id in that list, perform annotation group/set logic [for details, refer to handleAnnotationsWithRequests(requests, username)
sans requests, those are obtained from db based on job-id ]
'''
print('Received settings: {}'.format(str(settings)))
def job():
print("I'm working...")
#schedule.every(3).seconds.do(job)
#schedule.every(2).seconds.do(handleAnnotationsWithoutRequests, settings={'a': 'b'})
invoc_time = "10:33"
schedule.every().day.at(invoc_time).do(handleAnnotationsWithoutRequests, settings={'a': 'b'})
while True:
schedule.run_pending()
time.sleep(1)
但是在Django上下文中运行的这个(等效的)代码不会导致调用 .
def handleAnnotationsWithoutRequests(settings):
'''
From settings passed in, grab job-ids list
For each job-id in that list, perform annotation group/set logic [for details, refer to handleAnnotationsWithRequests(requests, username)
sans requests, those are obtained from db based on job-id ]
'''
log.info('Received settings: {}'.format(str(settings)))
def doSchedule(settings):
'''
with scheduler library
Based on time specified in settings, invoke .handleAnnotationsWithoutRequests(settings)
'''
#settings will need to be reconstituted from the DB first
#settings = {}
invocationTime = settings['running_at']
import re
invocationTime = re.sub(r'([AaPp][Mm])', "", invocationTime)
log.info("Invocation time to be used: {}".format(invocationTime))
schedule.every().day.at(invocationTime).do(handleAnnotationsWithoutRequests, settings=settings)
while True:
schedule.run_pending()
time.sleep(1)
所以来自 handleAnnotationsWithoutRequests()
的日志不会出现在控制台上 .
this scheduling library与Django兼容吗?是否有人可以引用我的用法样本?
我怀疑一些线程问题在这里工作 . 也许有更好的替代品可供使用?欢迎提出建议 .
先感谢您 .
1 回答
对于Web服务器,您可能不希望在进程中运行的某些内容:
https://github.com/Tivix/django-cron已经证明是一种可行的解决方案 .
还有重量级冠军Celery和Celerybeat .