詳解django中使用定時任務(wù)的方法
今天介紹在django中使用定時任務(wù)的兩種方式。
方式一: APScheduler
1)安裝:
pip install apscheduler
2)使用:
from apscheduler.scheduler import Scheduler from django.core.cache import cache # 實例化 sched = Scheduler() # 每30秒執(zhí)行一次 @sched.interval_schedule(seconds=30) def sched_test(): """ 測試-定時將隨機數(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)啟動定時任務(wù)
# 啟動定時任務(wù)
sched.start()
方式二: django-crontab
1) 安裝:
pip install django-crontab
2) 添加配置到INSTALL_APPS中
INSTALLED_APPS = ( 'django_crontab', )
3) 編寫定時函數(shù):
在django的app中新建一個test_crontab.py文件,把需要定時執(zhí)行的代碼放進去
import random from django.core.cache import cache def test(): """ 測試-定時將隨機數(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)編寫定時命令
Django為項目中每一個應(yīng)用下的management/commands目錄中名字沒有以下劃線開始的Python模塊都注冊了一個manage.py命令, 自定義一個命令如下: 必須定義一個繼承自BaseCommand的Command類, 并實現(xiàn)handle方法。
編寫appname/management/commands/test.py文件
import random from django.core.management.base import BaseCommand from 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, 會執(zhí)行handle()函數(shù)
5) 在settings.py中增加配置
# 運行定時函數(shù) CRONJOBS = [ ('*/1 * * * *', 'appname.test_crontab.test','>>/home/python/test_crontab.log') ] # 運行定時命令 CRONJOBS = [ ('*/1 * * * *', 'django.core.management.call_command', ['test'], {}, '>> /home/python/test.log'), ]
上面主要有3個參數(shù),分別表示: 定時任務(wù)執(zhí)行時間(間隔), 待執(zhí)行定時任務(wù), 將定時任務(wù)的信息追加到文件中
對于熟悉linux中定時任務(wù)crontab的同學(xué)可能對上面第一個參數(shù)的語法很親切。上面表示每隔1分鐘執(zhí)行一次代碼。
linux中的定時任務(wù)crontab的語法如下:
* * * * * command 分鐘(0-59) 小時(0-23) 每個月的哪一天(1-31) 月份(1-12) 周幾(0-6) shell腳本或者命令
例子:
0 6 * * * commands >> /tmp/test.log # 每天早上6點執(zhí)行, 并將信息追加到test.log中 0 */2 * * * commands # 每隔2小時執(zhí)行一次
有興趣的小伙伴可以深入研究下linux的crontab定時任務(wù)。
6) 添加并啟動定時任務(wù)
python manage.py crontab add
其它命令:
python manage.py crontab show: 顯示當(dāng)前的定時任務(wù) python manage.py crontab remove: 刪除所有定時任務(wù)
今天的定時任務(wù)就說到這里,有錯誤之處,歡迎交流指正!
相關(guān)文章
淺談django model的get和filter方法的區(qū)別(必看篇)
下面小編就為大家?guī)硪黄獪\談django model的get和filter方法的區(qū)別(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05如何利用python多線程爬取天氣網(wǎng)站圖片并保存
最近做個天 氣方面的APP需要用到一些天氣數(shù)據(jù),所以下面這篇文章主要給大家介紹了關(guān)于如何利用python多線程爬取天氣網(wǎng)站圖片并保存的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-11-11Sentry的安裝、配置、使用教程(Sentry日志手機系統(tǒng))
Sentry?是一個實時事件日志記錄和聚合平臺,由于ExceptionLess官方提供的客戶端只有.Net/.NetCore平臺和js的,本文繼續(xù)介紹另一個日志收集系統(tǒng)Sentry,感興趣的朋友一起看看吧2022-07-07