问题描述
我一直在使用 Django 开发一个网络应用程序,我很好奇是否有办法安排作业定期运行.
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 database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this.
有人知道如何设置吗?
澄清:我知道我可以设置一个 cron
作业来执行此操作,但我很好奇 Django 中是否有提供此功能的功能.我希望人们能够自己部署这个应用程序,而无需进行太多配置(最好是零配置).
To clarify: I know I can set up a cron
job to do this, but I'm curious if there is some feature in Django that provides this functionality. I'd like people to be able to deploy this app themselves without having to do much config (preferably zero).
我已经考虑通过简单地检查自上次向站点发送请求以来是否应该运行作业来追溯"触发这些操作,但我希望有一些更清晰的东西.
I've considered triggering these actions "retroactively" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.
推荐答案
我采用的一种解决方案是:
One solution that I have employed is to do this:
1) 创建一个 自定义管理命令,例如
1) Create a custom management command, e.g.
python manage.py my_cool_command
2) 使用 cron
(在 Linux 上)或 at
(在 Windows 上)在需要的时间运行我的命令.
2) Use cron
(on Linux) or at
(on Windows) to run my command at the required times.
这是一个简单的解决方案,不需要安装繁重的 AMQP 堆栈.但是,使用其他答案中提到的 Celery 之类的东西有很多好处.特别是,使用 Celery 很高兴不必将您的应用程序逻辑扩展到 crontab 文件中.然而,cron 解决方案非常适合中小型应用程序,并且您不希望有很多外部依赖项.
This is a simple solution that doesn't require installing a heavy AMQP stack. However there are nice advantages to using something like Celery, mentioned in the other answers. In particular, with Celery it is nice to not have to spread your application logic out into crontab files. However the cron solution works quite nicely for a small to medium sized application and where you don't want a lot of external dependencies.
在更高版本的 Windows 中,at
命令在 Windows 8、Server 2012 及更高版本中已弃用.您可以将 schtasks.exe
用于相同用途.
In later version of windows the at
command is deprecated for Windows 8, Server 2012 and above. You can use schtasks.exe
for same use.
**** 更新 ****这是新的链接用于编写自定义管理命令的 django 文档
**** UPDATE ****This the new link of django doc for writing the custom management command
这篇关于设置预定作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!