首页 > 解决方案 > 当模块A中的线程完成处理时如何通知模块B?

问题描述

我正在构建一个简单的爬虫,其中模块A每 24 小时扫描一次源以查找更改,并将新数据附加到磁盘上的 json 文件中。我使用模块B通过处理数据来更改数据。B我的问题是,当模块中的线程完成时,我需要以某种方式通知模块A。作为一名 JS 开发人员,我自然会求助于在模块中实现监听器的事件,B但不幸的是 python 没有。

最初我已经将模块转换为类,然后B通过扩展A,但很快意识到这并不好,因为某些模块:CD- 也会订阅A,将触发继承的同步逻辑(负责扫描并保存到本地 json)这是不需要的。

所以我想坚持使用模块和一种简单的方法来通知n多个模块,只要在模块中完成同步A

## Module A (storyHandler.py)

  def init(self):
    self.startCronJob()

  def startCronJob(self):
    ...
    t = threading.Timer(secs, self.syncStories)
    print('Cron for synching stories started ...')
    t.start()

  def syncStories(self):
    ...
    json = stories.to_json(orient='records')
    with open('data/stories/stories.json', 'w') as f:
      f.write(json)

    print('synching stories done!')
    #notify(stories) # <-- need to trigger a notification here


## Module B (storyCategoryClassifier.py)

def onNotify(stories): # module A should trigger this
   print('stories updated, start re-training category classifier')
   trainCategoryClassifier(stories)

def trainCategoryClassifier(stories):
   ...


## Module C (storyTypologyClassifier.py)

def onNotify(stories):
   print('stories updated, start re-training typology classifier')
   trainTypologyClassifier(stories)

def trainTypologyClassifier(stories):
   ...

非常感谢您的帮助!

标签: pythoneventspublish-subscribeobserver-patternnotify

解决方案


推荐阅读