简体   繁体   English

我怎么能经常检查 Python 3.8 中的值

[英]How could I constatly check a value in Python 3.8

So I'm programming a discord bot (using discord.py library) that should manage RPG characters and some other things, I want to manage leveling/xp with the bot.所以我正在编写一个应该管理 RPG 角色和其他一些东西的不和谐机器人(使用 discord.py 库),我想用机器人管理练级/xp。 My question is : is there a way that the bot will check every x seconds all the players xp amount ?我的问题是:有没有办法让机器人每 x 秒检查一次所有玩家的 xp 数量? I know I could write something like if character.xp == xp_amount in every parts that grant xp/create a function that does it and call in these parts, but it is possible to do it "passively" ?我知道我可以在每个部分中编写类似 if character.xp == xp_amount 的内容来授予 xp/create 一个执行它并在这些部分中调用的函数,但是可以“被动地”执行此操作吗?

You can use Python standard multiprocessing or threading module to check the value each x second.您可以使用 Python 标准多处理线程模块每 x 秒检查一次值。

Here's a code example for using threading module这是使用threading模块的代码示例

import time
import threading


VALUE = 10

def check_value(second: int) -> None:
    """Check global variable `VALUE` periodically

    Args:
        second (int): the checking interval
    """

    while True:
        if VALUE == 10:
            print('Value is 10')
        time.sleep(second)

if __name__ == "__main__":

    thread = threading.Thread(target=check_value, args=(2,))
    thread.start()
    # do other stuff here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM