Python DB 异步任务计划

问题描述 投票:0回答:1

我正在使用 telegram-bot 和 mysql-connector 以及 MySQL DB 来存储所有用户数据。

我每天需要运行查询 3 次:

UPDATE users SET rolls = rolls + 1 WHERE rolls < 12;

在主文件中,处理电报机器人的命令,我有一些功能,例如:

async def show_rolls(update: Update, context: ContextTypes.DEFAULT_TYPE, rolls):
    await update.message.reply_text(rolls)

if __name__ == '__main__':
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler('rolls', show_rolls))

每次用户使用

/rolls
命令机器人会显示他们有多少卷(存储在数据库中,他们每天都会获得 3 卷)

尝试了database.py文件中的schedule模块:

import schedule

schedule.every().day.at('15:00').do(add_rolls)
while True:
    schedule.run_pending()

add_rolls
函数只是执行我提到的查询,它按预期工作。

输入 while 循环会停止一切,当用户发送命令时,机器人不会响应。

还使用 telegram-bot 模块本身尝试了以下操作:

async def add_roll_schedule(context: ContextTypes.DEFAULT_TYPE) -> None:
    roll1_time = datetime.time(
        hour=18, minute=0, tzinfo=pytz.timezone('America/Sao_Paulo'))
    context.job_queue.run_daily(add_rolls, roll1_time)
    
   job = context.job
   await context.bot.send_message(job.chat_id, text='Rolls Added') 

但是我找不到每次机器人在线时调用此命令的方法,因为需要发送上下文。

python mysql telegram-bot python-telegram-bot
1个回答
0
投票

找到了使用 threading python 模块的解决方案。

为了提高效率,我不会显示我的确切功能,只是一个例如:

import schedule, time, threading

def hello():
    print('hello')

def check_schedule():
    while True:
         schedule.run_pending()
         time.sleep(1)

# Start a new thread only to check if there is any schedule pending.
threading.Thread(target=check_schedule).start() 

# Defining when the function is called
schedule.every().day.at('19:00').do(hello) 

如果有人有更有效/健康的方法来做到这一点,请告诉我! :)

© www.soinside.com 2019 - 2024. All rights reserved.