我正在撰寫一個代碼以mongodb每 5 分鐘插入一次資料,ON并且OFF
這里的問題是關鍵字中斷我的執行緒應該停止并退出代碼執行
將第一條記錄插入資料庫后,我time.sleep(300)將使腳本進入睡眠狀態,并且在我的終端上會出現以下行 ->Press enter to kill the running thread :
萬一如果我改變主意不想跑
只需當我從鍵盤按回車鍵時,正在運行且處于睡眠狀態的執行緒應該停止并退出
我的目標是根據用戶的輸入停止執行緒
我的代碼:
import datetime
import threading
import pymongo
import time
from pymongo import MongoClient
dbUrl = pymongo.MongoClient("mongodb://localhost:1245/")
dbName = dbUrl["student"]
dbCollectionName = dbName["student_course"]
def doremon():
return "Hi Friends"
def insert_to_mongodb():
global kill_the_running_thread
while (not kill_the_running_thread):
note_start_time = datetime.datetime.now()
msg = doremon()
note_end_time = datetime.datetime.now()
dt = {"message": msg, "start_time": note_start_time, "end_time": note_end_time}
rec_id1 = dbCollectionName.insert_one(dt)
time.sleep(300)
def main():
global kill_the_running_thread
kill_the_running_thread = False
my_thread = threading.Thread(target=insert_to_mongodb)
my_thread.start()
input("Press enter to kill the running thread : ")
kill_the_running_thread = True
# Calling main
main()
uj5u.com熱心網友回復:
將全域變數作為哨兵與睡眠結合使用時會出現問題。問題是睡眠可能剛剛開始(在 OP 的情況下為 5 分鐘),因此執行緒可能需要將近 5 分鐘才能意識到它應該終止。
一個首選(我)的技術是使用佇列。您可以在佇列上指定超時,當然,它幾乎會立即回應傳遞給它的任何資料。這是一個例子:
from threading import Thread
from queue import Queue, Empty
def process(queue):
while True:
try:
queue.get(timeout=5)
break
except Empty as e:
pass
print('Doing work')
queue = Queue()
thread = Thread(target=process, args=(queue,))
thread.start()
input('Press enter to terminate the thread: ')
queue.put(None)
thread.join()
process() 函式將在佇列中阻塞最多 5 秒(在此示例中)。如果佇列中沒有任何內容,它將完成它的作業。如果有什么東西(我們只是傳遞 None 作為觸發器),它將立即終止
uj5u.com熱心網友回復:
您可以嘗試自定義類,如下所示:
import datetime
import threading
import pymongo
import time
from pymongo import MongoClient
dbUrl = pymongo.MongoClient("mongodb://localhost:1245/")
dbName = dbUrl["student"]
dbCollectionName = dbName["student_course"]
class ThreadWithKill(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._target = kwargs.get('target')
self._kill = threading.Event()
self._sleep_duration = 300 # 5 minutes
def run(self):
while True:
# If no kill signal is set, sleep for the duration of the interval.
# If kill signal comes in while sleeping, immediately wake up and handle
self._target() # execute passed function
is_killed = self._kill.wait(self._sleep_duration)
if is_killed:
break
def kill(self):
self._kill.set()
def doremon():
return "Hi Friends"
def insert_to_mongodb():
note_start_time = datetime.datetime.now()
msg = doremon()
note_end_time = datetime.datetime.now()
dt = {"message": msg, "start_time": note_start_time, "end_time": note_end_time}
rec_id1 = dbCollectionName.insert_one(dt)
def main():
my_thread = ThreadWithKill(target=insert_to_mongodb)
my_thread.start()
input("Press enter to kill the running thread : ")
my_thread.kill()
if __name__ == "__main__":
main()
這樣就不需要kill_the_running_thread變數了。你需要自己測驗一下,因為我沒有 mongodb。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504149.html
標籤:Python mongodb python-多线程 蟒蛇时间表 蟒蛇调度
