如何在Django中設(shè)置定時(shí)任務(wù)的方法示例
Django 作為后端Web開發(fā)框架,有時(shí)候我們需要用到定時(shí)任務(wù)來或者固定頻次的任務(wù)來執(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)建測試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)容,我都在對應(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)容
打開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 后臺添加計(jì)劃任務(wù)
訪問“http://localhost:8000/admin/”,在celery的管理頁面里,選擇Periodic tasks,進(jìn)行任務(wù)添加。選擇對應(yīng)的任務(wù),設(shè)置定時(shí)或者周期時(shí)間
3.2 啟動定時(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窗口會看到任務(wù)的輸入信息
3.3 啟動單次的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會輸出信息 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命令,則寫django.core.management.call_command
參數(shù)3:方法的位置參數(shù)列表(默認(rèn)值:[]),如果執(zhí)行django-admin命令,則填寫所需執(zhí)行的命令,例如我們在polls中已經(jīng)定義過的closepoll
參數(shù)4:方法的關(guān)鍵字參數(shù)的dict(默認(rèn)值:{})
參數(shù)5:執(zhí)行l(wèi)og存放位置(即重定向到文件,默認(rèn):'')
django-crontab任務(wù)加載:
django-crontab任務(wù)加載比較簡單,只需要運(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è)會更新定時(shí)任務(wù)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
五個(gè)Pandas?實(shí)戰(zhàn)案例帶你分析操作數(shù)據(jù)
pandas是基于NumPy的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的。Pandas納入了大量庫和一些標(biāo)準(zhǔn)的數(shù)據(jù)模型,提供了高效操作大型數(shù)據(jù)集的工具。pandas提供大量快速便捷地處理數(shù)據(jù)的函數(shù)和方法。你很快就會發(fā)現(xiàn),它是使Python強(qiáng)大而高效的數(shù)據(jù)分析環(huán)境的重要因素之一2022-01-01
python機(jī)器學(xué)習(xí)基礎(chǔ)線性回歸與嶺回歸算法詳解
這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)基礎(chǔ)線性回歸與嶺回歸算法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
Python利用pymupdf實(shí)現(xiàn)簡單的PDF閱讀器
這篇文章主要為大家詳細(xì)介紹了Python如何利用pymupdf實(shí)現(xiàn)簡單的PDF閱讀器,并展示了PDF文件的內(nèi)容,文中的示例代碼講解詳細(xì),需要的可以了解一下2023-08-08
pytorch中節(jié)約顯卡內(nèi)存的方法和技巧
顯存不足是很多人感到頭疼的問題,畢竟能擁有大量顯存的實(shí)驗(yàn)室還是少數(shù),而現(xiàn)在的模型已經(jīng)越跑越大,模型參數(shù)量和數(shù)據(jù)集也越來越大,所以這篇文章給大家總結(jié)了一些pytorch中節(jié)約顯卡內(nèi)存的方法和技巧,需要的朋友可以參考下2023-11-11

