zoukankan      html  css  js  c++  java
  • django项目中遇到要实现定时任务

    django项目中遇到要实现定时任务,所以选用了简单易用的django-crontab插件。

    1、安装 django-crontab

    pip install django-crontab

    2、定时要执行的脚本

    先写个简单的测试脚本。
    crontab/crons.py

    import datetime
    
    def update_stock_status():
        start_time = datetime.datetime.now()
        print(start_time, ", begin update_stock_status cron task...")

    3、配置

    在项目的配置文件 settings.py 中,加上下列信息:

    # add django-crontab app
    INSTALLED_APPS = [
        ...
        'django_crontab',
    ]
    
    # cron tasks
    CRONJOBS = [
        ('*/5 * * * *', 'crontab.crons.update_stock_status', '>>' + os.path.join(BASE_DIR, 'logs/crons.log'))
    ]
    """ python3 manage.py crontab add 添加定时任务 python3 manage.py crontab remove 删除定时任务 python3 manage.py crontab show 查看定时任务 * * * * * command 分钟(0-59) 小时(0-23) 每个月的哪一天(1-31) 月份(1-12) 周几(0-6) shell脚本或者命令 0 6 * * * commands >> /tmp/test.log # 每天早上6点执行, 并将信息追加到test.log中 """
    • crontab.crons.update_stock_status :crontab 表示目录;crons 表示crons.py文件;update_stock_status 表示要执行的函数。
    • ‘>>’ + os.path.join(BASE_DIR, ‘logs/crons.log’):表示把定时任务的日志写到crons.log 文件中。

    4、启动定时任务

    # 其实是把定时任务写入系统的 crontab 中,在系统中使用 crontab -l 可以看到
    python manage.py crontab add
    # 删除定时任务
    python manage.py crontab remove
    # 查看定时任务
    python manage.py crontab show
  • 相关阅读:
    从内存中加载并启动一个exe
    使用Hamcrest增强JUnit的测试能力
    Delphi编译指令说明
    Delphi 64与32位的差异
    获取exe文件窗口抓图,将memo转化为JPG输出
    Delphi 的 Utf-8 转换
    我的第一个破解软件,试验成功!
    Qt之QComboBox(基本应用、代理设置)
    常见寄存器以及常见汇编指令,常见爆破指令 good
    大神级回答exists与in的区别
  • 原文地址:https://www.cnblogs.com/zmdComeOn/p/12369817.html
Copyright © 2011-2022 走看看