【问题标题】:Schedule task in Django using schedule package使用 schedule 包在 Django 中安排任务
【发布时间】:2017-09-29 18:01:52
【问题描述】:

我正在尝试学习如何使用 schedule 包在 Django 中安排任务。这是我添加到视图中的代码。我应该提到我只有一个视图,所以我需要在我的索引视图中运行调度程序。我知道代码逻辑存在问题,它只会渲染调度程序并且会陷入循环。你能告诉我我该怎么做用吗?

def job():
    print "this is scheduled job", str(datetime.now())

def index(request):
    schedule.every(10).second.do(job())
    while True:
        schedule.run_pending()
        time.sleep(1)

    objs= objsdb.objects.all()
    template = loader.get_template('objtest/index.html')
    context= { 'objs': objs}
    return HttpResponse(template.render(context, request))

【问题讨论】:

    标签: django schedule


    【解决方案1】:

    您选择了错误的方法。如果你想安排一些应该定期运行的东西,你不应该在 Web 请求中这样做。请求永远不会结束,因为 wile 循环 - 浏览器和网络服务器非常不喜欢这种行为。

    相反,您可能想要编写一个独立运行并负责调用您的任务的management command

    此外,您可能还想阅读Django - Set Up A Scheduled Job? - 他们还介绍了其他方法,例如 AMPQ 和 cron。但这些会取代您选择的日程安排模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2020-10-12
      • 2019-06-03
      • 2011-07-21
      • 1970-01-01
      • 2012-01-16
      • 2011-11-28
      相关资源
      最近更新 更多