簡體   English   中英

如何在True內每隔X秒運行代碼-python

[英]How to run code every x seconds inside while true - python

我需要每x秒在while循環內執行代碼,而不停止循環工作

我嘗試使用線程和鎖組合,但仍然無法正常工作。 我正在使用python 3.7.4,pycharm 2019.2

#!/usr/bin/env python3

import configparser
import logging
import threading
import time

import ts3

__all__ = ["notify_bot"]

logging.basicConfig(filename='ts3bot.log',
                    level=logging.INFO,
                    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s",
                    )

logging.getLogger().addHandler(logging.StreamHandler())
def notify_bot(ts3conn, config, lock):
    logging.info("Start Notify Bot ...")
    lock.acquire()
    ts3conn.exec_("servernotifyregister", event="server")
    lock.release()
    while True:
        event = ts3conn.wait_for_event()
        try:
            reasonid_ = event[0]["reasonid"]
        except KeyError:
            continue
        if reasonid_ == "0":
            logging.info("User joined Lobby:")
            logging.info(event[0])
            servergroups = event[0]['client_servergroups']
            guestname = event[0]['client_nickname']
            lock.acquire()
            if not set(servergroups):
                print(f"s1 {guestname}")
            else:
                print(f"s2{guestname}")
            lock.release()
    return None
def keep_alive(ts3conn, lock):
    while True:
        logging.info("Send keep alive!")
        lock.acquire()
        ts3conn.send_keepalive()
        lock.release()
        time.sleep(5)
if __name__ == "__main__":
    logging.info("Start TS Bot ...")
    config = configparser.ConfigParser()
    config.sections()
    config.read("settings_test.ini")
    logging.info("Config loaded!")
    HOST = config['server']['url']
    PORT = config['server']['query_port']
    USER = config['server']['query_user']
    PASS = config['server']['query_pw']
    SID = config['server']['sid']
    NAME = config['bot']['name']

    logging.info("Connecting to query interface ...")
    URI = f"telnet://{USER}:{PASS}@{HOST}:{PORT}"
    try:
        with ts3.query.TS3ServerConnection(URI) as ts3conn:
            ts3conn.exec_("use", sid=SID)

            ts3conn.query("clientupdate", client_nickname="x123d")
            logging.info("Connected!")

            lock = threading.Lock()

            notify_thread = threading.Thread(target=notify_bot, args=(ts3conn, config, lock), daemon=True,
                                             name="notify")
            keep_alive_thread = threading.Thread(target=keep_alive, args=(ts3conn, lock), daemon=True,
                                                 name="keep_alive")
            notify_thread.start()
            keep_alive_thread.start()
            keep_alive_thread.join()
            notify_thread.join()
    except KeyboardInterrupt:
        logging.INFO(60 * "=")
        logging.info("TS Bot terminated by user!")
        logging.INFO(60 * "=")

在為1個加入服務器且不執行任何操作的人運行工作之后,不要發送保持活動狀態並且根本不工作

您可以使用Bibio TIME您可以從python官方網站( https://docs.python.org/3/library/time.html )進行檢查

就個人而言,對於簡單的事情,我發現_thread庫更容易。 這是可以在線程中運行的函數,以及啟動該線程的示例:

import _thread
def mythread(arg1):
    while True:
        time.sleep(arg1)
        do.whatever()
_thread.start_new_thread(mythread, (5,))

需要注意的重要事情是我傳遞給_thread.start_new_thread函數的第二個參數。 必須是一個元組,這就是為什么在5之后有一個逗號的原因。即使您的函數不需要任何參數,也必須傳遞一個元組。

我正在使用時間模塊和線程,我進行了一些更改,它似乎可以正常工作

#!/usr/bin/env python3

import configparser
import logging
import threading
import time
import ts3
logging.basicConfig(filename='ts3bot.log',
                    level=logging.INFO,
                    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s",
                    )
logging.getLogger().addHandler(logging.StreamHandler())

def notify_bot(ts3conn):
    logging.info("Start Notify Bot ...")
    ts3conn.exec_("servernotifyregister", event="server")
    while True:
        event = ts3conn.wait_for_event()
        try:
            reasonid_ = event[0]["reasonid"]
        except KeyError:
            continue
        if reasonid_ == "0":
            logging.info("User joined Lobby:")
            logging.info(event[0])
            servergroups = event[0]['client_servergroups']
            guestname = event[0]['client_nickname']
            if not set(servergroups):
                print(f"s1 {guestname}")
            else:
                print(f"s2{guestname}")
    return None
def keep_alive(ts3conn, time):
    while True:
        logging.info("Send keep alive!")
        ts3conn.send_keepalive()
        time.sleep(20)
if __name__ == "__main__":
    logging.info("Start TS Bot ...")
    config = configparser.ConfigParser()
    config.sections()
    config.read("settings_test.ini")
    logging.info("Config loaded!")
    HOST = config['server']['url']
    PORT = config['server']['query_port']
    USER = config['server']['query_user']
    PASS = config['server']['query_pw']
    SID = config['server']['sid']
    NAME = config['bot']['name']

    logging.info("Connecting to query interface ...")
    URI = f"telnet://{USER}:{PASS}@{HOST}:{PORT}"
    try:
        with ts3.query.TS3ServerConnection(URI) as ts3conn:
            ts3conn.exec_("use", sid=SID)

            ts3conn.query("clientupdate", client_nickname="x123d")
            logging.info("Connected!")
            notify_thread = threading.Thread(target=notify_bot, args=(ts3conn,), daemon=True,
                                             name="notify")
            keep_alive_thread = threading.Thread(target=keep_alive, args=(ts3conn, time), daemon=True,
                                                 name="keep_alive")
            notify_thread.start()
            keep_alive_thread.start()
            keep_alive_thread.join()
            notify_thread.join()
    except KeyboardInterrupt:
        logging.INFO(60 * "=")
        logging.info("TS Bot terminated by user!")
        logging.INFO(60 * "=")

看起來ts3conn.send_keepalive()出錯,當我刪除它時,代碼可以正常工作,當我添加它時,發送ts3conn.send_keepalive()一次后代碼停止工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM