Django的Cron示例 [英] Example Cron with Django

查看:95
本文介绍了Django的Cron示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上搜集了Django中预定工作的工作示例。但是我只能找到方法,但是没有给出任何例子。

I've serched among the internet 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 shecudled 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()

之后,如果您看下面的代码,一个python脚本将每1分钟被调用一次。创建一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆