【问题标题】:How to get django-cron to work automatically如何让 django-cron 自动工作
【发布时间】:2013-04-05 14:14:16
【问题描述】:

我试图让django-cron 工作,但它没有。我按照指令 here 设置我的 cron,但问题是我的作业仅在我在命令行上键入 python manage.py runcrons 时运行,并且作业不是每 5 分钟运行一次。我不知道还能做什么。我已经阅读了crontabschronograph 上的其他文件,但我很困惑。我是否将 crontabs 与 cron 或 chronograph 一起安装,或者仅使用 django-cron 才能使 cron 正常工作。另外,我如何让我的工作自动运行。在文档 here 我读到 Now everytime you run the management command python manage.py runcrons all the crons will run if required. Depending on the application the management command can be called from the Unix crontab as often as required. Every 5 minutes usually works for most of my applications. 。这是什么意思。我在这里想念什么。我迷路了。帮助

Settings.py

CRON_CLASSES = (
"myapp.views.MyCronJob",
)

INSTALLED_APPS = (

'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_cron',

'django.contrib.admin',
'django.contrib.admindocs',
'myapp',


)

views.py

from django_cron import CronJobBase, Schedule
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 10 # every 10 min

schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'my_app.my_cron_job'    # a unique code

def do(self):
    print "10 min Cron"
    theJob()

我应该提到我在 windows 平台上使用 pycharm 来运行 django...

【问题讨论】:

  • 你找到这个问题的解决方案了吗?

标签: django cron crontab cron-task django-cron


【解决方案1】:

问题的根源在于操作系统。 Webserver 不是那种调用你的 cronjobs 的守护进程,它只是处理 web 请求。要在 Windows 上调用周期性任务,您需要使用 Windows 任务计划程序:

What is the Windows version of cron?

解决问题的其他方法是在 celery beat 模式下启动 celery deaemon。

http://celeryproject.org/

http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html

这是一个更难的方法,如果你有非常简单的应用程序你不需要使用 celery。但在很多情况下,队列是最好的解决方案。

【讨论】:

  • 如果您在 Windows 计算机上使用 Git Bash 工作,它会工作吗?
【解决方案2】:

改为安装 django-crontab。

pip install django-crontab  

更改您的 settings.py 以包含 django-crontab

INSTALLED_APPS = (
'django_crontab',
...
)

CRONJOBS = [
('*/5 * * * *', 'myproject.cron.my_scheduled_job')
]

在你的应用目录中创建一个 cron.py 文件

def my_scheduled_job():
   #do something

每次包含或更新您的 cron 作业时运行此程序。

python manage.py crontab add

运行您的本地服务器来测试您的 cron:

python manage.py runserver

你就完成了! :)

【讨论】:

  • 出于某种原因,它对我不起作用。你能帮我解决这个问题吗?
  • 我无法正常工作。我的工作没有得到执行。有什么要补充的吗?
  • 为什么是 /5 ?没有这个我们就不能写吗? 1 周我们必须添加什么?
【解决方案3】:

您可以像这样以编程方式执行“runcrons”:

from django.core.management import call_command
call_command('runcrons')

例如,我将以上几行放在我的 wsgi.py 中

【讨论】:

    猜你喜欢
    • 2011-09-24
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多