python - 如何为每个 URL 提供自己的线程
问题描述
我一直在研究一个小型 PoC,我一直在努力提高我对线程的了解,但不幸的是我被卡住了,我在这里,
import time
found_products = []
site_catalog = [
"https://www.graffitishop.net/Sneakers",
"https://www.graffitishop.net/T-shirts",
"https://www.graffitishop.net/Sweatshirts",
"https://www.graffitishop.net/Shirts"
]
def threading_feeds():
# Create own thread for each URL as we want to run concurrent
for get_links in site_catalog:
monitor_feed(link=get_links)
def monitor_feed(link: str) -> None:
old_payload = product_data(...)
while True:
new_payload = product_data(...)
if old_payload != new_payload:
for links in new_payload:
if links not in found_products:
logger.info(f'Detected new link -> {found_link} | From -> {link}')
# Execute new thread as we don't want to block this function wait for filtering() to be done before continue
filtering(link=found_link)
else:
logger.info("Nothing new")
time.sleep(60)
continue
def filtering(found_link):
...
1 - 我目前正在尝试做一个监视器,我有多个链接开始,我的计划是我希望每个 url 同时运行,而不是需要等待 1 接 1:
def threading_feeds():
# Create own thread for each URL as we want to run concurrent
for get_links in site_catalog:
monitor_feed(link=get_links)
我怎样才能做到这一点?
2 - 如果我们似乎发现一个新产品已经出现在给定的 URL 里面monitor_feed
,我该如何设置一个新线程来执行调用filtering(link=found_link)
?我不想在它继续循环返回之前等待它完成,While True
而是它应该filtering(link=found_link)
在后台执行,同时它仍然执行monitor_feed
解决方案
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(monitor_feed, site_catalog)
您可以使用ThreadPoolExecutor。
推荐阅读
- json - Laravel - 如何从 JSON 中提取值到文本框中
- windows - "heroku config | grep REDIS" 如何在 windows cmd 上制定
- windows - Aero Snap 后将 WinForms 窗口恢复到正确位置
- java - Java 中 AM/PM 的时差
- c++ - QT 多线程和更新 GUI
- java - 部署到快照本地未在快照中找到
- r - 当 2 个不同的数据帧在 R 中的 2 列上匹配时,如何向列添加布尔值?
- javascript - PWA 的更新图标不显示是否在更新之前通过 chrome desktop/android 或 osx/ios 安装
- netlogo - Netlogo 代码在同一个补丁上添加人员
- javascript - HTML表格多选+过滤