欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python事件驅(qū)動(dòng)event實(shí)現(xiàn)詳解

 更新時(shí)間:2018年11月21日 11:23:51   作者:brucewong0516  
這篇文章主要為大家詳細(xì)介紹了python事件驅(qū)動(dòng)event實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

所有的計(jì)算機(jī)程序都可以大致分為兩類:腳本型(單次運(yùn)行)和連續(xù)運(yùn)行型(直到用戶主動(dòng)退出)。

腳本型:腳本型的程序包括最早的批處理文件以及使用Python做交易策略回測(cè)等等,這類程序的特點(diǎn)是在用戶啟動(dòng)后會(huì)按照編程時(shí)設(shè)計(jì)好的步驟一步步運(yùn)行,所有步驟運(yùn)行完后自動(dòng)退出。

連續(xù)運(yùn)行型:連續(xù)運(yùn)行型的程序包含了操作系統(tǒng)和絕大部分我們?nèi)粘J褂玫能浖鹊龋@類程序啟動(dòng)后會(huì)處于一個(gè)無(wú)限循環(huán)中連續(xù)運(yùn)行,直到用戶主動(dòng)退出時(shí)才會(huì)結(jié)束。

一、連續(xù)運(yùn)行型程序

我們要開發(fā)的交易系統(tǒng)就是屬于連續(xù)運(yùn)行型程序,而這種程序根據(jù)其計(jì)算邏輯的運(yùn)行機(jī)制不同,又可以粗略的分為時(shí)間驅(qū)動(dòng)和事件驅(qū)動(dòng)兩種。

1.1 時(shí)間驅(qū)動(dòng)

時(shí)間驅(qū)動(dòng)的程序邏輯相對(duì)容易設(shè)計(jì),簡(jiǎn)單來(lái)說(shuō)就是讓電腦每隔一段時(shí)間自動(dòng)做一些事情。這個(gè)事情本身可以很復(fù)雜、包括很多步驟,但這些步驟都是線性的,按照順序一步步執(zhí)行下來(lái)。

from time import sleep
def demo():
 print('BB')
while True:
 demo()
 sleep(1.0)

時(shí)間驅(qū)動(dòng)的程序本質(zhì)上就是每隔一段時(shí)間固定運(yùn)行一次腳本。盡管腳本自身可以很長(zhǎng)、包含非常多的步驟,但是我們可以看出這種程序的運(yùn)行機(jī)制相對(duì)比較簡(jiǎn)單、容易理解。

時(shí)間驅(qū)動(dòng)的程序在量化交易方面還存在一些其他的缺點(diǎn):如浪費(fèi)CPU的計(jì)算資源、實(shí)現(xiàn)異步邏輯復(fù)雜度高等等。

1.2 事件驅(qū)動(dòng)

與時(shí)間驅(qū)動(dòng)對(duì)應(yīng)的就是事件驅(qū)動(dòng)的程序:當(dāng)某個(gè)新的事件被推送到程序中時(shí),程序立即調(diào)用和這個(gè)事件相對(duì)應(yīng)的處理函數(shù)進(jìn)行相關(guān)的操作。

舉個(gè)例子:

有些人喜歡的某個(gè)公眾號(hào),然后去關(guān)注這個(gè)公眾號(hào),哪天這個(gè)公眾號(hào)發(fā)布了篇新的文章,沒(méi)多久訂閱者就會(huì)在微信里收到這個(gè)公眾號(hào)推送的新消息,如果感興趣就打開來(lái)閱讀。

上面公眾號(hào)例子可以翻譯為,監(jiān)聽(tīng)器(訂閱者)監(jiān)聽(tīng)了(關(guān)注了)事件源(公眾號(hào)),當(dāng)事件源的發(fā)送事件時(shí)(公眾號(hào)發(fā)布文章),所有監(jiān)聽(tīng)該事件的監(jiān)聽(tīng)器(訂閱者)都會(huì)接收到消息并作出響應(yīng)(閱讀文章)。

  • 公眾號(hào)為事件源
  • 訂閱者為事件監(jiān)聽(tīng)器
  • 訂閱者關(guān)注公眾號(hào),相當(dāng)于監(jiān)聽(tīng)器監(jiān)聽(tīng)了事件源
  • 公眾號(hào)發(fā)布文章這個(gè)動(dòng)作為發(fā)送事件
  • 訂閱者收到事件后,做出閱讀文章的響應(yīng)動(dòng)作

事件驅(qū)動(dòng)主要包含以下元素和操作函數(shù):

1.2.1 元素

  • 事件源
  • 事件監(jiān)聽(tīng)器
  • 事件對(duì)象

1.2.2 操作函數(shù)

  • 監(jiān)聽(tīng)動(dòng)作
  • 發(fā)送事件
  • 調(diào)用監(jiān)聽(tīng)器響應(yīng)函數(shù)

現(xiàn)在用python實(shí)現(xiàn)來(lái)實(shí)現(xiàn)上述的業(yè)務(wù)邏輯,先看流程圖:


1.2.3 EventManager事件管理類代碼如下:

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 13:51:31 2018

@author: 18665
"""
# 系統(tǒng)模塊
from queue import Queue, Empty
from threading import *
########################################################################
class EventManager:
 #----------------------------------------------------------------------
 def __init__(self):
  """初始化事件管理器"""
  # 事件對(duì)象列表
  self.__eventQueue = Queue()
  # 事件管理器開關(guān)
  self.__active = False
  # 事件處理線程
  self.__thread = Thread(target = self.__Run)
  self.count = 0
  # 這里的__handlers是一個(gè)字典,用來(lái)保存對(duì)應(yīng)的事件的響應(yīng)函數(shù)
  # 其中每個(gè)鍵對(duì)應(yīng)的值是一個(gè)列表,列表中保存了對(duì)該事件監(jiān)聽(tīng)的響應(yīng)函數(shù),一對(duì)多
  self.__handlers = {}
 #----------------------------------------------------------------------
 def __Run(self):
  """引擎運(yùn)行"""
  print('{}_run'.format(self.count))
  while self.__active == True:
   try:
    # 獲取事件的阻塞時(shí)間設(shè)為1秒
    event = self.__eventQueue.get(block = True, timeout = 1) 
    self.__EventProcess(event)
   except Empty:
    pass
   self.count += 1
 #----------------------------------------------------------------------
 def __EventProcess(self, event):
  """處理事件"""
  print('{}_EventProcess'.format(self.count))
  # 檢查是否存在對(duì)該事件進(jìn)行監(jiān)聽(tīng)的處理函數(shù)
  if event.type_ in self.__handlers:
   # 若存在,則按順序?qū)⑹录鬟f給處理函數(shù)執(zhí)行
   for handler in self.__handlers[event.type_]:
    handler(event)
  self.count += 1
 #----------------------------------------------------------------------
 def Start(self):
  """啟動(dòng)"""
  print('{}_Start'.format(self.count))
  # 將事件管理器設(shè)為啟動(dòng)
  self.__active = True
  # 啟動(dòng)事件處理線程
  self.__thread.start()
  self.count += 1
 #----------------------------------------------------------------------
 def Stop(self):
  """停止"""
  print('{}_Stop'.format(self.count))
  # 將事件管理器設(shè)為停止
  self.__active = False
  # 等待事件處理線程退出
  self.__thread.join()
  self.count += 1
 #----------------------------------------------------------------------
 def AddEventListener(self, type_, handler):
  """綁定事件和監(jiān)聽(tīng)器處理函數(shù)"""
  print('{}_AddEventListener'.format(self.count))
  # 嘗試獲取該事件類型對(duì)應(yīng)的處理函數(shù)列表,若無(wú)則創(chuàng)建
  try:
   handlerList = self.__handlers[type_]
  except KeyError:
   handlerList = []
 self.__handlers[type_] = handlerList
  # 若要注冊(cè)的處理器不在該事件的處理器列表中,則注冊(cè)該事件
  if handler not in handlerList:
   handlerList.append(handler)
  print(self.__handlers)
  self.count += 1
 #----------------------------------------------------------------------
 def RemoveEventListener(self, type_, handler):
  """移除監(jiān)聽(tīng)器的處理函數(shù)"""
  print('{}_RemoveEventListener'.format(self.count))
  try:
   handlerList = self.handlers[type_]
   # 如果該函數(shù)存在于列表中,則移除
   if handler in handlerList:
    handlerList.remove(handler)
   # 如果函數(shù)列表為空,則從引擎中移除該事件類型
   if not handlerList:
    del self.handlers[type_]
  except KeyError:
   pass
  self.count += 1
 #----------------------------------------------------------------------
 def SendEvent(self, event):
  """發(fā)送事件,向事件隊(duì)列中存入事件"""
  print('{}_SendEvent'.format(self.count))
  self.__eventQueue.put(event)
  self.count += 1
########################################################################
"""事件對(duì)象"""
class Event:
 def __init__(self, type_=None):
  self.type_ = type_  # 事件類型
  self.dict = {}   # 字典用于保存具體的事件數(shù)據(jù)

1.2.4 測(cè)試代碼

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 13 13:50:45 2018

@author: 18665
"""

# encoding: UTF-8
import sys
from datetime import datetime
from threading import *
#sys.path.append('D:\\works\\TestFile')
#print(sys.path)
from eventManager import *

#事件名稱 新文章
EVENT_ARTICAL = "Event_Artical"

#事件源 公眾號(hào)
class PublicAccounts:
 def __init__(self,eventManager):
  self.__eventManager = eventManager

 def WriteNewArtical(self):
  #事件對(duì)象,寫了新文章
  event = Event(type_=EVENT_ARTICAL)
  event.dict["artical"] = u'如何寫出更優(yōu)雅的代碼\n'
  
  #發(fā)送事件
  self.__eventManager.SendEvent(event)
  print(u'公眾號(hào)發(fā)送新文章\n')

#監(jiān)聽(tīng)器 訂閱者
class Listener:
 def __init__(self,username):
  self.__username = username

 #監(jiān)聽(tīng)器的處理函數(shù) 讀文章
 def ReadArtical(self,event):
  print(u'%s 收到新文章' % self.__username)
  print(u'正在閱讀新文章內(nèi)容:%s' % event.dict["artical"])

"""測(cè)試函數(shù)"""
#--------------------------------------------------------------------
def test():
 # 實(shí)例化監(jiān)聽(tīng)器
 listner1 = Listener("thinkroom") #訂閱者1
 listner2 = Listener("steve")  #訂閱者2
 # 實(shí)例化事件操作函數(shù)
 eventManager = EventManager()

 #綁定事件和監(jiān)聽(tīng)器響應(yīng)函數(shù)(新文章)
 eventManager.AddEventListener(EVENT_ARTICAL, listner1.ReadArtical)
 eventManager.AddEventListener(EVENT_ARTICAL, listner2.ReadArtical)
 # 啟動(dòng)事件管理器,# 啟動(dòng)事件處理線程
 eventManager.Start()

 publicAcc = PublicAccounts(eventManager)
 timer = Timer(2, publicAcc.WriteNewArtical)
 timer.start()

if __name__ == '__main__':
 test()

通過(guò)eventManager可以實(shí)現(xiàn)事件觸發(fā)的邏輯,當(dāng)事件觸發(fā)時(shí),推送事件到線程里運(yùn)行。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論