2017-05-30 29 views
1

我想問一下:自從我們開始一個python程序以來,如何編寫一個計算1小時的python程序?自從python程序啓動以來,如何計算1小時?

我舉一個例子: - 我們在17:00:00啓動python程序 - 運行1小時後(在18:00:00),python程序將打印一條消息通知1小時已經通過。

我可以找出一個python程序。首先,我記錄開始程序的時間(稱爲start_time),然後我連續記錄下次(稱爲end_time)。如果(end_time-start_time == 1小時),則它打印消息。

不過看起來程序浪費了太多的CPU性能!我需要一個CPU性能較低的程序。

編輯: 我需要如下。

我有一個線程名稱wait_an_event_thread。它是一個阻塞線程。如果未設置事件trigger,則此線程被阻止。 在阻塞時間內,如果已經過了1小時,此線程會打印出一條消息。 這是我的期望。

以前,我說我下次連續錄音(電話end_time)。這意味着我打算從阻塞線程更改爲非阻塞線程,因爲我不知道如何在阻塞的線程中打印消息,如果已經過了1小時。但看來非阻塞線程需要這麼多的CPU性能。

這是我的代碼:
我的意料:阻塞線程

def wait_an_event_thread(trigger): 
    trigger.wait() 
    # If 1 hour has been passed, it print a message 
    # How to print message if 1 hour has been passed in this blocking thread if the "trigger" event is not set?? 

trigger = threading.Event() 
wait_an_event_thread = threading.Thread(name='wait_an_event_thread', 
         target=wait_an_event_thread, 
         args=(trigger,)) 
wait_an_event_thread.start() 
+4

您可以使用['Timer'](https://docs.python.org/3/library/threading.html?highlight=timer#threading.Timer)。你還應該包括你迄今爲止嘗試過的最簡單的例子,以便其他人能夠更好地幫助你。 –

+0

我編輯我的帖子爲我的例子。你能讀懂嗎? – jackbk

+0

你有一個同名的函數和var,它會導致問題。此外,如果你想要她的幫助,你需要給她加標籤@IljaEverilä – IsaacDj

回答

1

事實證明你需要使用超時參數Event.wait(),並檢查事件已在返回或不設置:

def wait_an_event_thread(trigger): 
    while not trigger.wait(3600): 
     print "1 hour has passed" 

    # Do what must be done when triggered 

trigger = threading.Event() 
the_thread = threading.Thread(name='wait_an_event_thread', 
           target=wait_an_event_thread, 
           args=(trigger,)) 
the_thread.start() 

這會繼續打印小時的診斷消息(ish)間隔,如果沒有設置Event。 Event.wait()might behave badly if your system clock jumps backwards

4
import threading 

def func(): 
    #your code here 

t = threading.Timer(3600, func) 
t.start() 

More details in documentation

感謝@IljaEverilä的修正和改進

+0

比較小時使用秒數?不需要秒級別分辨率! – dsgdfg

+0

@dsgdfg責怪創建線程模塊的好人 – IsaacDj

+0

任何程序員都不會使用外部計時器!如何處理垃圾數據,異常,錯誤等。功能時間不等於系統時間。什麼是事件? – dsgdfg

0

你可以採取多線程的優勢並創建一個單獨的線程t帽子與其他代碼分開運行。該線程只需睡1小時,然後打印「1小時已通過」,然後再睡一個小時。

說得以代碼的形式,你需要這樣的事情:

​​

,並在你的main()添加類似:

import _thread 

    if __name__=="__main__": 
    # 
    # your init code here 
    # 
    try: 
    _thread.start_new_thread(print_message_every_interval, \ 
    ("Timer-1h", "One hour have passed", 3600)) 
    except Exception as e: 
    print('could not start new thread') 
    print(e) 
    # 
    # the rest of your code here 
    # 

當然也有很多多線程庫可以用來使代碼看起來很花哨。像threading模塊一樣。

你可以找到更多關於這個話題在這裏: https://www.tutorialspoint.com/python3/python_multithreading.htm

0

我建議一小時後您使用

`time.sleep(t)` 

其中t是儘可能高,而不會影響你的程序。

+0

睡眠不好如果不能在一個線程! – dsgdfg

0

啓動一個線程,它會在每小時後調用一個函數並打印消息。 你可以用你的主函數寫這樣的代碼: 進口線程

def print(): 
    print "One Hour has been passed" 

t = threading.Timer(3600, print) 
t.start() 

這將調用打印功能每隔一小時後,打印的消息。

+0

不宜用內建的名字 – IsaacDj

+0

'高清打印():打印...'嘗試和Python 3的運行它,已經修正'打印「」''到打印(「」)',你就會明白爲什麼你從不覆蓋內置的名稱;) –

相關問題