使用 Django 的示例 Cron [英] Example Cron with Django
问题描述
我在互联网上搜索了 Django 中预定作业的工作示例.但我只能找到如何去做,但没有给出例子.有人可以分享一个使用 cron 运行计划任务的 Django 框架的工作示例吗?
I've searched the internet for a working example of a scheduled job in Django. But I can only find how to do it, but no example is given. Can someone share a working example of the Django framework running a scheduled task with cron?
推荐答案
首先创建一个 自定义管理命令.此命令将用于将任务添加到 crontab.这是我的自定义命令的示例:
First of all create a custom admin command. This command will be used to add the task to the crontab. Here is an example of my custom command:
cron.py
from django.core.management.base import BaseCommand, CommandError
import os
from crontab import CronTab
class Command(BaseCommand):
help = 'Cron testing'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
#init cron
cron = CronTab(user='your_username')
#add new cron job
job = cron.new(command='python <path_to>/example.py >>/tmp/out.txt 2>&1')
#job settings
job.minute.every(1)
cron.write()
之后,如果您查看下面的代码,将会每 1 分钟调用一次 Python 脚本.创建一个 example.py
文件,并在其中添加您希望每 1 分钟创建一次的功能.
After that, if you have a look at the code below, a python script is going to be invoked every 1 minute. Create an example.py
file and add it there the functionality that you want to be made every 1 minute.
一切准备好添加定时任务,只需从项目django目录调用如下命令即可:
All is prepared to add the scheduled job, just invoke the following command from the project django directory:
python manage.py cron
要验证 cron 作业是否已成功添加,请调用以下命令:
To verify that the cron job was added successfully invoke the following command:
crontab -l
您应该会看到如下内容:
You should see something like this:
* * * * * <path_to>/example.py
要调试example.py,只需调用这个命令:
To debug the example.py, simply invoke this coomand:
tail -f /tmp/out.txt
这篇关于使用 Django 的示例 Cron的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!