
本文介绍如何基于 Python 的 pyTelegramBotAPI(telebot)构建一个轻量级定时提醒系统,精准在指定时间(如出发前24小时)向用户发送一次 Telegram 消息,避免重复触发。
本文介绍如何基于 python 的 `pytelegrambotapi`(telebot)构建一个轻量级定时提醒系统,精准在指定时间(如出发前24小时)向用户发送一次 telegram 消息,避免重复触发。
在 Telegram Bot 开发中,常见的需求是「仅在特定时刻发送一条提醒消息」——例如航班出发前 24 小时通知用户。但 schedule 等轮询库默认设计为周期性任务,难以天然支持「未来某刻仅执行一次」的语义;而 APScheduler 虽支持一次性任务(add_job(..., trigger='date')),却会因 Bot 进程重启导致任务丢失,缺乏持久化保障。
更可靠、轻量且适用于中小型 Bot 的方案是:自主维护一个后台线程,持续检查当前时间,并与预设的触发时间比对,满足条件即发送消息并标记完成。以下是一个生产就绪的实现示例:
import telebot
import time
import datetime
import threading
bot = telebot.TeleBot('YOUR_BOT_TOKEN')
# 存储用户信息与待触发提醒(实际项目建议用数据库或 Redis)
user_reminders = {} # {chat_id: {'departure_time': datetime, 'sent': bool}}
@bot.message_handler(commands=['setdeparture'])
def set_departure(message):
try:
# 示例:/setdeparture 2025-06-15 14:30 → 提醒时间为 6月14日 14:30
_, date_str, time_str = message.text.split()
departure = datetime.datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
reminder_time = departure - datetime.timedelta(days=1) # 提前24小时
user_reminders[message.chat.id] = {
'reminder_time': reminder_time,
'sent': False
}
bot.reply_to(message, f"✅ 已设置出发提醒:{departure},将在 {reminder_time} 发送通知。")
except (ValueError, IndexError):
bot.reply_to(message, "❌ 格式错误,请使用:/setdeparture YYYY-MM-DD HH:MM")
def background_checker():
while True:
now = datetime.datetime.now()
# 遍历所有待提醒用户
for chat_id, data in list(user_reminders.items()):
if not data['sent'] and now >= data['reminder_time']:
try:
bot.send_message(chat_id, "⏰ 温馨提示:您明日即将出发,请提前做好准备!")
data['sent'] = True
print(f"[INFO] Reminder sent to {chat_id} at {now}")
except Exception as e:
print(f"[ERROR] Failed to send to {chat_id}: {e}")
time.sleep(30) # 每30秒检查一次,平衡精度与资源消耗
# 启动后台检查线程(守护线程,避免阻塞 polling)
checker_thread = threading.Thread(target=background_checker, daemon=True)
checker_thread.start()
bot.polling(none_stop=True)✅ 关键设计说明:
- 使用 daemon=True 确保线程随主程序退出而终止,避免僵尸进程;
- time.sleep(30) 平衡实时性与 CPU 占用,对单次提醒精度(±30秒)完全可接受;
- user_reminders 字典模拟状态存储,真实部署务必替换为持久化方案(如 SQLite 记录 chat_id, trigger_at, is_sent 字段);
- 所有 bot.send_message() 调用均包裹 try/except,防止网络异常中断检查循环。
⚠️ 注意事项:
- 切勿在主线程中使用 time.sleep() 或阻塞操作,否则会导致 Bot 无法响应新消息;
- 若需支持海量用户或高精度(秒级)触发,推荐升级至 APScheduler + SQLAlchemy 或云函数(如 AWS EventBridge);
- Bot 服务器需保持 24/7 运行,若使用免费云服务(如 Render、Railway),注意休眠机制可能中断线程。
该方案简洁、可控、零依赖,适合快速落地个人或中小团队的定时提醒场景。核心思想不是“调度”,而是“主动守候”——让 Bot 自己成为时间的守门人。

















