django-crontab中的细节

若其中存在中文,必须在文件开头加上:#coding=UTF-8
全局变量的使用技巧在函数外部声明一个变量,在函数内部修改该全局变量之前先用global声明,修改才能生效。代码如下:

#coding=UTF-8
post_list = []
def test():
    print "--------任务开始--------"
    from app.models import Tasks
    import time
    now = int(time.time())
    global post_list
    post_list = Tasks.objects.filter(expire_time__lt=now)
    post_list = list(post_list)
    item_list(post_list)
    print Tasks.objects.filter(expire_time__lt=now).query


def item_list(post_list):
    print "--------请求队列--------"
    if len(post_list):
        print post_list
        item = post_list[0]
        del_post(item)

def del_post(item):
    print "--------请求参数--------"
    import requests
    crc32 = item.crc32+""
    url = item.url+""
    url = url.replace("http://", "")
    url = url.replace("https://", "")
    url = url.replace("/", "")
    post_data = {"crc32": crc32, "url": url}
    print post_data
    resp = requests.post("http://api.shawdo.com/api/admin/public/oneDataOutput", data=post_data)
    print "--------请求结果--------"
    print resp.text
    if resp.status_code == 200:
        global post_list
        del post_list[0]
        item_list(post_list)
        if len(post_list) == 0:
            print "--------任务完成--------"

如果不声明post_list ,那么所有函数中引用post_list 都是[],这样我们就不能使用不算变化的post_list去做队列了。
settings.py中写入的内容:

INSTALLED_APPS = [
    。。。。。。
    'django_crontab',
]
//python_site为文件目录,cron为文件名称,test为函数名称
CRONJOBS = [
    ('*/1 * * * *', 'python_site.cron.test', '>>/home/test.log')
]

settings.py配置完了之后需要python manage.py crontab add 将任务添加到crontab中。然后运行django即可,运行django:python manage.py runserver。remove可以删除,其实add也可以覆盖掉之前的,add之后要重启crontab服务:/etc/init.d/cron restart。查看crontab状态的话:ps aux | grep cron

不过还是推荐使用linux自带的crontab,这里需要注意的是使用shell脚本去调用你的py文件
shell中应该这样写:

python /home/test.py

然后crontab再去定时执行shell脚本

crontab使用
编辑crontab任务

crontab -e

添加一条计划任务,使用shell脚本去控制需要执行的代码

*/1 * * * * sh /home/test.sh

shell中

python /home/test.py
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值