django-crontab

django-cromtab实现定时任务

参考:https://www.jianshu.com/p/1def9226158d
 '''
 首先安装插件:pip install django-crontab
 然后在setting的installed app下
 INSTALLED_APPS = (
    ...
    'django_crontab', #注意是_不是-
)
 '''   
三、然后在在test APP下新建cron.py:
    #
    def test_job():
    # cursor = connection(db='default')
    # sql = """"""
    # test = Test('哈哈')
    with open('a.txt', 'w') as f:
        f.write('Hello, world!')

    print(6666)
    return 1
四、同时在 settings.py 文件中添加 CRONJOBS 配置,内容如下:
CRONJOBS = [
    ('*/1 * * * *', 'cele.cron.test_job', '>>/tmp/test.log')
]

其中:

第一个参数是 cron 表达式,定义定时任务的执行时间。
第二个参数是要执行的模块和函数。
第三个参数是执行定时脚本时日志文件的路径。
五、执行:python manage.py crontab add 
然后每隔1分钟就能在/tmp/test.log中看到一行666的记录,生成的a.txt文件在~下

django-crontab结合django:
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: 
@software: PyCharm
@file: cron.py
@time: 2018/6/14 10:06
"""
# from django.db import connection
# from cele.models import Test
import os
import django
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_django.settings')
django.setup()
from cele.models import Test
def test_job():
    # cursor = connection(db='default')
    # sql = """"""
    test = Test(name='哈哈')
    test.save()
    with open('a.txt', 'w') as f:
        f.write('Hello, world!')

    print(6666)
    return 1

test_job()
CRONJOBS = [
    # ('48 10 * * *', 'cele.cron.py.test_job'),
    # ('*/1 * * * *', 'cele.cron.test_job', '>>/tmp/test.log')
]
每隔1分钟再数据库中插入一条数据
原文地址:https://www.cnblogs.com/lajiao/p/9182592.html