所有匹配主题的 Gist threading

timmy / 使用 threading.Timer 延遲開啟網頁

0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
此程式透過 threading.Timer 延遲指定秒數後,自動開啟指定的 URL。適用於自動化測試、提醒功能或延遲啟動特定網頁,確保主程式不中斷的情況下執行非同步操作。
1 import threading
2 import webbrowser
3
4 def open_url(url):
5 """ 開啟指定的 URL """
6 webbrowser.open(url, new=2)
7
8 # 設定延遲時間(秒)
9 delay = 2
10 url = "https://www.example.com"

timmy / Flask 簡單 Web 伺服器

0 喜欢
0 派生
1 文件
最后活跃于 9 months ago
此程式使用 Flask 建立一個簡單的 Web 伺服器,並允許使用命令列指定埠號。預設監聽所有網卡 (0.0.0.0),支援多執行緒處理,提高併發能力,適合作為輕量級 API 或網頁應用的基礎。
1 # 匯入 Flask 框架,用於建立 Web 應用程式
2 from flask import Flask
3 import argparse # 匯入 argparse 來解析命令列參數
4
5 # 建立 Flask 應用程式實例
6 app = Flask(__name__)
7
8 # 定義根路由,當用戶訪問 "/" 時返回 "Hello, Flask!"
9 @app.route('/')
10 def home():
最后活跃于 10 months ago
這段程式碼結合了 Python 的 asyncio 和 threading,透過 loop.run_in_executor 在背景執行同步的 blocking_sleep(),避免阻塞 asyncio 事件迴圈。這允許 async_sleep() 在等待時仍能執行其他非同步任務,適用於需要在 asyncio 應用程式中處理阻塞性 I/O 操作(如 time.sleep())的情境。
1 import asyncio
2 import threading
3 import time
4
5 async def delayed_execution():
6 # 在這裡執行延遲後的任務
7 print("Delayed execution")
8
9 def blocking_sleep(seconds):
10 time.sleep(seconds)
最后活跃于 10 months ago
這段程式碼使用 Python 的 threading 模組來實現非同步延遲執行。當 async_sleep(seconds) 被呼叫時,它會建立一個新的執行緒來執行 sleep() 函式,而不會阻塞主執行緒。這允許主程式繼續執行其他任務,同時在指定時間後執行 delayed_execution()。這對於需要非同步延遲執行的應用場景,如計時器或背景任務,特別有用。
1 import threading
2 import time
3
4 def delayed_execution():
5 # 在這裡執行延遲後的任務
6 print("Delayed execution")
7
8 def async_sleep(seconds):
9 def sleep():
10 time.sleep(seconds)
上一页 下一页