【问题标题】:How schedule a job (Django, Python)如何安排作业(Django、Python)
【发布时间】:2018-11-01 16:41:52
【问题描述】:

我想创建一个滚动到所有 10 分钟的作业。 我找到了一个很好的例子here。问题是程序在等待期间冻结,我的其他网址被阻止。 在我之后是因为 while True:

有没有办法在不解决这个问题的情况下做到这一点?

语音代码:

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

**************************************************** ********************。

我找到了正确的方法。这是link: 为了使其正常工作,我删除了这部分:

# time.sleep(20)
# print('Checkpoint **************************')
# time.sleep(30)
# print('Bye -----------------------')

这是有效的代码:

import threading
class ThreadingExample(object):
    """ Threading example class
    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=10):
        """ Constructor
        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background', self.interval)
            pk_info_semaine = job_temp.objects.all()
            for a in pk_info_semaine:
                print('num_semaine:',a.num_semaine,'user_id:',a.user_id)
            time.sleep(self.interval)

example = ThreadingExample()

谢谢大家,感谢作者:Paris Nakita Kejser Here

【问题讨论】:

  • 也许schedule FAQ 可以帮助你
  • 根据您所做的事情,您可能想查看其他使用 django 构建的用于执行计划任务的框架...看起来schedule 不是其中之一
  • 这个问题的答案很好:stackoverflow.com/questions/573618/…

标签: python django runtime schedule


【解决方案1】:

您可以使用 celery + celerybeat 与 Django 一起运行计划任务。您可以将您的方法编写为 celery 任务,并在 settings.py 文件中添加一个条目,以使该任务每 10 分钟运行一次。该任务将在其 on 线程中运行,因此不会阻塞您的应用程序。

语音链接到 celery: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

【讨论】:

  • 谢谢,我会按照指示进行的。我会就最终结果与您联系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2013-07-28
  • 2017-08-18
  • 2014-04-02
  • 2020-01-05
相关资源
最近更新 更多