如何在Django中設(shè)置定時(shí)任務(wù)的方法示例
Django 作為后端Web開(kāi)發(fā)框架,有時(shí)候我們需要用到定時(shí)任務(wù)來(lái)或者固定頻次的任務(wù)來(lái)執(zhí)行某段代碼,這時(shí)我們就要用到Celery了。Django中有一個(gè)中間件:Django-celery
環(huán)境:
- Python 3.6
- Django為小于1.8版本
- Celery為3.1版本
第一步安裝:django-celery
pip install django-celery
第二步:配置celery和任務(wù)
創(chuàng)建測(cè)試django環(huán)境:
django-admin.py createproject test django-admin.py startapp demo
創(chuàng)建好的項(xiàng)目布局如下:
- proj/ - manage.py - proj/ - __init__.py - celery.py - settings.py - urls.py - demo/ - migrations - __init__.py - admin.py - apps.py - models.py - tasks.py - tests.py - views.py
2.1 配置celery.py文件
需要替換的內(nèi)容,我都在對(duì)應(yīng)的行后提示了,剩下的內(nèi)容默認(rèn)就好
創(chuàng)建test/test/celery.py文件,內(nèi)容如下:
from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') # “proj.settings”替換為你的項(xiàng)目信息:test.settings app = Celery('proj') # 這里的proj替換為你的項(xiàng)目名稱:test # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
2.2 配置項(xiàng)目的init.py中配置celery內(nèi)容
打開(kāi)test/test/__init_.py文件,添加內(nèi)容:
from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',)
2.3 在task.py中添加計(jì)劃任務(wù)
編輯test/demo/task.py文件,添加計(jì)劃任務(wù),內(nèi)容如下:
# Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers)
第三步:任務(wù)執(zhí)行
運(yùn)行django項(xiàng)目: python manage.py runserver
3.1 后臺(tái)添加計(jì)劃任務(wù)
訪問(wèn)“http://localhost:8000/admin/”,在celery的管理頁(yè)面里,選擇Periodic tasks,進(jìn)行任務(wù)添加。選擇對(duì)應(yīng)的任務(wù),設(shè)置定時(shí)或者周期時(shí)間
3.2 啟動(dòng)定時(shí)的celery服務(wù)
注意:celery依賴redis服務(wù),需要提前運(yùn)行redis服務(wù):`redis-server`
# 以下兩個(gè)命令在不同的shell窗口里執(zhí)行,需要在django的目錄下 python manager.py celery beat -l info #接收定時(shí)任務(wù)的命令 python manager.py celery worker -l info #執(zhí)行定時(shí)任務(wù)的命令,此shell窗口會(huì)看到任務(wù)的輸入信息
3.3 啟動(dòng)單次的celery服務(wù)
注意:celery依賴redis服務(wù),需要提前運(yùn)行redis服務(wù):`redis-server`
python manager.py shell # 進(jìn)到django的shell里 from demo.task import mul, xsum # 導(dǎo)入task任務(wù) a = mul() b = xsum() # 執(zhí)行a, b會(huì)輸出信息 a(1,2) b(1)
PS:django-crontab實(shí)現(xiàn)Django定時(shí)任務(wù)
django-crontab安裝:
pip install django-crontab
django-crontab加入:只需要將django-crontab加入到settings.py的INSTALLED_APPS即可。如下代碼:
INSTALLED_APPS = ( 'django_crontab', ... )
django-crontab配置:settings.py中加入django-crontab的命令即可:
CRONJOBS = [ ('47 11 * * *', 'django.core.management.call_command', ['closepoll'],{},'>> /var/run.log'), ]
格式:
參數(shù)1:定時(shí) 例如47 11 * * * 表示每天的11時(shí)47分執(zhí)行
參數(shù)2:方法的python模塊路徑,如果執(zhí)行django-admin命令,則寫(xiě)django.core.management.call_command
參數(shù)3:方法的位置參數(shù)列表(默認(rèn)值:[]),如果執(zhí)行django-admin命令,則填寫(xiě)所需執(zhí)行的命令,例如我們?cè)趐olls中已經(jīng)定義過(guò)的closepoll
參數(shù)4:方法的關(guān)鍵字參數(shù)的dict(默認(rèn)值:{})
參數(shù)5:執(zhí)行l(wèi)og存放位置(即重定向到文件,默認(rèn):'')
django-crontab任務(wù)加載:
django-crontab任務(wù)加載比較簡(jiǎn)單,只需要運(yùn)行 python manage.py crontab add 即可
查看已經(jīng)激活的任務(wù)使用 python manage.py crontab show
刪除已經(jīng)有的任務(wù)使用 python manage.py crontab remove
如果你修改了任務(wù)記得一定要使用 python manage.py crontab add 這個(gè)會(huì)更新定時(shí)任務(wù)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
keras分類模型中的輸入數(shù)據(jù)與標(biāo)簽的維度實(shí)例
這篇文章主要介紹了keras分類模型中的輸入數(shù)據(jù)與標(biāo)簽的維度實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07Python正則表達(dá)式re.search()用法詳解
re是Python中最常見(jiàn)的正則表達(dá)式模塊,常用方法包括compile,match,findall,finditer,search,split,sub等,下面這篇文章主要給大家介紹了關(guān)于Python正則表達(dá)式re.search()用法詳解的相關(guān)資料,需要的朋友可以參考下2022-09-09python3爬蟲(chóng)獲取html內(nèi)容及各屬性值的方法
今天小編就為大家分享一篇python3爬蟲(chóng)獲取html內(nèi)容及各屬性值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12使用django的ORM框架按月統(tǒng)計(jì)近一年內(nèi)的數(shù)據(jù)方法
今天小編就為大家分享一篇使用django的ORM框架按月統(tǒng)計(jì)近一年內(nèi)的數(shù)據(jù)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07Python基于pip實(shí)現(xiàn)離線打包過(guò)程詳解
這篇文章主要介紹了Python基于pip實(shí)現(xiàn)離線打包過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05利用Anaconda簡(jiǎn)單安裝scrapy框架的方法
今天小編就為大家分享一篇利用Anaconda簡(jiǎn)單安裝scrapy框架的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06python 將字符串中的數(shù)字相加求和的實(shí)現(xiàn)
這篇文章主要介紹了python 將字符串中的數(shù)字相加求和的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07