Python脚本超时重试机制设计:失败立即重试,最多3次
定时任务跑挂是量化交易中最常见的事故来源。凌晨2点的行情数据抓取脚本,因为一次网络抖动直接退出,整个策略数据链断裂。解决这个问题不需要复杂的框架,一个设计良好的重试机制就够了。
本文给出一个可直接落地的Python超时重试方案,核心设计原则:失败立即重试、最多3次、指数退避、完整日志。
为什么需要重试机制
量化场景下,脚本失败通常来自三类原因:
- 瞬时网络故障:DNS解析失败、TCP连接重置、SSL握手超时
- API限频:交易所或数据源对请求频率的限制,返回429或超时
- 下游服务不稳定:数据库连接池耗尽、消息队列短暂不可用
这些错误有一个共同特点:重试大概率能成功。但如果脚本直接退出,整个任务链就断了。
基础版:简单的重试装饰器
先看一个最精简的实现,用装饰器包装任意函数,失败自动重试:
python
import functools
import time
import logging
from typing import Callable, Type, Tuple
logger = logging.getLogger(__name__)
def retry(
max_retries: int = 3,
base_delay: float = 1.0,
exceptions: Tuple[Type[Exception], ...] = (Exception,),
backoff_factor: float = 2.0,
) -> Callable:
"""
重试装饰器
Args:
max_retries: 最大重试次数(不含第一次尝试)
base_delay: 初始重试延迟(秒)
exceptions: 需要重试的异常类型
backoff_factor: 退避倍数,每次重试延迟 = base_delay * backoff_factor^(retry_count-1)
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
retry_count = 0
while retry_count <= max_retries:
try:
return func(*args, **kwargs)
except exceptions as e:
retry_count += 1
if retry_count > max_retries:
logger.error(f"Function {func.__name__} failed after {max_retries} retries. Error: {e}")
raise
delay = base_delay * (backoff_factor ** (retry_count - 1))
logger.warning(
f"Function {func.__name__} failed (attempt {retry_count}/{max_retries}). "
f"Error: {e}. Retrying in {delay:.2f}s..."
)
time.sleep(delay)
return None # 实际不会执行到这里
return wrapper
return decorator
使用方式:
python
@retry(max_retries=3, base_delay=1.0, exceptions=(TimeoutError, ConnectionError))
def fetch_kline_data(symbol: str, interval: str) -> dict:
"""模拟获取K线数据"""
# 这里是实际的API调用
response = api_client.get_kline(symbol, interval)
return response.json()
这个版本解决了基本问题,但有几个明显的缺陷:
- 没有超时控制(如果函数本身卡死不抛异常,重试永远不会触发)
- 日志信息不够结构化
- 无法区分"可重试错误"和"致命错误"
进阶版:带超时控制和完整日志
引入 signal 模块实现函数级超时控制,同时增加结构化日志:
python
import signal
import functools
import time
import logging
import json
from typing import Callable, Type, Tuple, Any, Dict
logger = logging.getLogger(__name__)
class TimeoutError(Exception):
"""自定义超时异常"""
pass
def timeout_handler(signum, frame):
raise TimeoutError(f"Function timed out after {signum} seconds")
def with_timeout(seconds: int) -> Callable:
"""
函数超时装饰器(仅适用于Unix/Linux/macOS)
Args:
seconds: 超时秒数
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 设置信号处理器
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
# 取消定时器
signal.alarm(0)
return result
return wrapper
return decorator
class RetryConfig:
"""重试配置"""
def __init__(
self,
max_retries: int = 3,
base_delay: float = 1.0,
backoff_factor: float = 2.0,
timeout: int = 30,
retry_exceptions: Tuple[Type[Exception], ...] = (TimeoutError, ConnectionError, OSError),
fatal_exceptions: Tuple[Type[Exception], ...] = (ValueError, KeyError, TypeError),
):
self.max_retries = max_retries
self.base_delay = base_delay
self.backoff_factor = backoff_factor
self.timeout = timeout
self.retry_exceptions = retry_exceptions
self.fatal_exceptions = fatal_exceptions
def retry_with_config(config: RetryConfig) -> Callable:
"""
带完整配置的重试装饰器
- 支持超时控制
- 区分可重试异常和致命异常
- 结构化日志输出
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
retry_count = 0
attempt_logs = []
while retry_count <= config.max_retries:
attempt_start = time.time()
try:
# 如果配置了超时,则包装函数
if config.timeout > 0:
result = with_timeout(config.timeout)(func)(*args, **kwargs)
else:
result = func(*args, **kwargs)
# 成功执行,记录日志
log_entry = {
"event": "success",
"function": func.__name__,
"attempt": retry_count + 1,
"duration_ms": round((time.time() - attempt_start) * 1000, 2),
}
logger.info(json.dumps(log_entry))
return result
except config.fatal_exceptions as e:
# 致命错误,不重试,直接抛出
logger.error(
json.dumps({
"event": "fatal_error",
"function": func.__name__,
"error": str(e),
"attempt": retry_count + 1,
})
)
raise
except config.retry_exceptions as e:
retry_count += 1
duration_ms = round((time.time() - attempt_start) * 1000, 2)
log_entry = {
"event": "retry",
"function": func.__name__,
"attempt": retry_count,
"max_retries": config.max_retries,
"error": str(e),
"error_type": type(e).__name__,
"duration_ms": duration_ms,
}
if retry_count > config.max_retries:
log_entry["event"] = "exhausted"
logger.error(json.dumps(log_entry))
raise
delay = config.base_delay * (config.backoff_factor ** (retry_count - 1))
log_entry["next_retry_delay"] = delay
logger.warning(json.dumps(log_entry))
time.sleep(delay)
except Exception as e:
# 未知异常,按可重试处理
retry_count += 1
logger.warning(
json.dumps({
"event": "unknown_error",
"function": func.__name__,
"error": str(e),
"attempt": retry_count,
})
)
if retry_count > config.max_retries:
raise
time.sleep(config.base_delay * (config.backoff_factor ** (retry_count - 1)))
return None
return wrapper
return decorator
使用示例:
python
# 配置重试参数
config = RetryConfig(
max_retries=3,
base_delay=1.0,
backoff_factor=2.0,
timeout=10, # 10秒超时
retry_exceptions=(TimeoutError, ConnectionError, OSError),
fatal_exceptions=(ValueError, KeyError),
)
@retry_with_config(config)
def fetch_order_book(symbol: str) -> dict:
"""获取订单簿数据"""
# 模拟可能超时的API调用
import random
if random.random() < 0.3:
raise ConnectionError("Simulated network failure")
return {"symbol": symbol, "bids": [], "asks": []}
# 测试
for i in range(5):
try:
result = fetch_order_book("BTCUSDT")
print(f"Success: {result}")
except Exception as e:
print(f"Failed: {e}")
Windows兼容方案:线程超时
上面的 signal 方案在Windows上不可用。如果脚本需要在Windows环境运行(比如某些交易终端),改用线程实现超时:
python
import threading
import functools
import time
from concurrent.futures import ThreadPoolExecutor, TimeoutError
def with_timeout_thread(seconds: int) -> Callable:
"""线程超时装饰器(跨平台)"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(func, *args, **kwargs)
try:
return future.result(timeout=seconds)
except TimeoutError:
raise TimeoutError(f"Function {func.__name__} timed out after {seconds}s")
return wrapper
return decorator
注意:线程方案有局限性,超时后线程仍会在后台运行,可能产生僵尸线程。对于IO密集型任务(网络请求、数据库操作)适用,对于CPU密集型任务不推荐。
实战:定时任务中的完整应用
下面是一个完整的定时任务示例,结合了重试机制和任务调度:
python
import schedule
import time
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('task_retry.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger("scheduled_task")
# 定义任务配置
retry_config = RetryConfig(
max_retries=3,
base_delay=2.0,
backoff_factor=2.0,
timeout=15,
retry_exceptions=(TimeoutError, ConnectionError, OSError),
fatal_exceptions=(ValueError,)
)
@retry_with_config(retry_config)
def sync_market_data():
"""同步市场数据到本地数据库"""
logger.info("Starting market data sync...")
# 模拟网络请求
time.sleep(2)
# 模拟随机失败
import random
if random.random() < 0.4:
raise ConnectionError("API rate limit exceeded")
# 模拟数据处理
data = {"timestamp": datetime.now().isoformat(), "data": "some_market_data"}
# 写入数据库
# db.insert(data)
logger.info("Market data sync completed")
return True
def run_scheduled_task():
"""定时任务入口"""
try:
sync_market_data()
except Exception as e:
logger.error(f"Task failed permanently: {e}")
# 可以在这里发送告警通知
# send_alert(f"Task failed: {e}")
# 每5分钟执行一次
schedule.every(5).minutes.do(run_scheduled_task)
logger.info("Scheduler started. Press Ctrl+C to exit.")
while True:
schedule.run_pending()
time.sleep(1)
设计要点总结
-
失败立即重试 :第一次重试不等待,立即执行。上面的代码中
base_delay=1.0,实际第一次重试延迟1秒,如果希望立即重试,可以设置base_delay=0或单独处理第一次重试。 -
最多3次 :
max_retries=3表示总共4次尝试(1次原始+3次重试)。根据经验,3次重试已经覆盖95%以上的瞬时故障。 -
指数退避 :重试延迟为
base_delay * backoff_factor^(n-1),即1s、2s、4s。避免在服务恢复前疯狂重试。 -
日志记录:每条重试记录包含函数名、尝试次数、错误类型、耗时、下次重试延迟。这些信息对排查问题至关重要。
-
区分异常类型:可重试异常(网络错误)和致命异常(参数错误)分开处理,避免无意义的重试。
进一步优化方向
- Jitter抖动:在退避延迟中加入随机抖动,避免多个任务同时重试造成雪崩
- 熔断机制:连续失败超过阈值后,暂时停止重试,进入冷却期
- 重试状态持久化:对于长任务,将重试状态保存到Redis,避免进程重启后丢失
- 异步重试 :使用
asyncio和aiohttp实现异步重试,不阻塞主线程
重试机制是容错设计的第一道防线。在量化交易系统中,一个健壮的重试机制能省去大量人工运维时间。上面的代码可以直接复制到项目中使用,根据自己的业务场景调整超时时间和重试次数。
更多关于Python定时任务、量化系统架构的内容,请继续关注本站更新。