今天介紹在django中使用定時(shí)任務(wù)的兩種方式。
方式一: APScheduler
1)安裝:
pip install apscheduler
2)使用:
from apscheduler.scheduler import Schedulerfrom django.core.cache import cache# 實(shí)例化sched = Scheduler() # 每30秒執(zhí)行一次@sched.interval_schedule(seconds=30)def sched_test(): """ 測(cè)試-定時(shí)將隨機(jī)數(shù)保存到redis中 :return: """ seed = "123456789" sa = [] for i in range(4): sa.append(random.choice(seed)) code = ''.join(sa) cache.set("test_"+code, code)3)啟動(dòng)定時(shí)任務(wù)
# 啟動(dòng)定時(shí)任務(wù)
sched.start()
方式二: django-crontab
1) 安裝:
pip install django-crontab
2) 添加配置到INSTALL_APPS中
INSTALLED_APPS = ('django_crontab',)3) 編寫定時(shí)函數(shù):
在django的app中新建一個(gè)test_crontab.py文件,把需要定時(shí)執(zhí)行的代碼放進(jìn)去
import random from django.core.cache import cache def test(): """ 測(cè)試-定時(shí)將隨機(jī)數(shù)保存到redis中 :return: """ seed = "123456789" sa = [] for i in range(4): sa.append(random.choice(seed)) code = ''.join(sa) cache.set("test_"+code, code)4)編寫定時(shí)命令
Django為項(xiàng)目中每一個(gè)應(yīng)用下的management/commands目錄中名字沒(méi)有以下劃線開(kāi)始的Python模塊都注冊(cè)了一個(gè)manage.py命令, 自定義一個(gè)命令如下: 必須定義一個(gè)繼承自BaseCommand的Command類, 并實(shí)現(xiàn)handle方法。
編寫appname/management/commands/test.py文件
import random from django.core.management.base import BaseCommandfrom django.core.cache import cache class Command(BaseCommand): """ 自定義命令 """ def handle(self, *args, **options): """ 自定義命令 :return: """ seed = "123456789" sa = [] for i in range(4): sa.append(random.choice(seed)) code = ''.join(sa) cache.set("test_"+code, code)定義完成后,執(zhí)行python manage.py test, 會(huì)執(zhí)行handle()函數(shù)
5) 在settings.py中增加配置
# 運(yùn)行定時(shí)函數(shù)CRONJOBS = [ ('*/1 * * * *', 'appname.test_crontab.test','>>/home/python/test_crontab.log')] # 運(yùn)行定時(shí)命令CRONJOBS = [ ('*/1 * * * *', 'django.core.management.call_command', ['test'], {}, '>> /home/python/test.log'),] 上面主要有3個(gè)參數(shù),分別表示: 定時(shí)任務(wù)執(zhí)行時(shí)間(間隔), 待執(zhí)行定時(shí)任務(wù), 將定時(shí)任務(wù)的信息追加到文件中
對(duì)于熟悉linux中定時(shí)任務(wù)crontab的同學(xué)可能對(duì)上面第一個(gè)參數(shù)的語(yǔ)法很親切。上面表示每隔1分鐘執(zhí)行一次代碼。
linux中的定時(shí)任務(wù)crontab的語(yǔ)法如下:
* * * * * command分鐘(0-59) 小時(shí)(0-23) 每個(gè)月的哪一天(1-31) 月份(1-12) 周幾(0-6) shell腳本或者命令
例子:
0 6 * * * commands >> /tmp/test.log # 每天早上6點(diǎn)執(zhí)行, 并將信息追加到test.log中0 */2 * * * commands # 每隔2小時(shí)執(zhí)行一次
有興趣的小伙伴可以深入研究下linux的crontab定時(shí)任務(wù)。
6) 添加并啟動(dòng)定時(shí)任務(wù)
python manage.py crontab add
其它命令:
python manage.py crontab show: 顯示當(dāng)前的定時(shí)任務(wù)python manage.py crontab remove: 刪除所有定時(shí)任務(wù)
今天的定時(shí)任務(wù)就說(shuō)到這里,有錯(cuò)誤之處,歡迎交流指正!
新聞熱點(diǎn)
疑難解答
圖片精選