如何根據電腦時鐘,在每個小時的5分鐘。10分鐘。15分鐘,。。。。45分鐘,50分鐘,55,分鐘,00分鐘開始運行程式,
例如:
#00:00
print("hello")
#00:05
print("hello")
#00:10
print("hello")
#00:15
print("hello")
#00:20
print("hello")
*
*
*
*
#00:50
print("hello")
#00:55
print("hello")
#01:00
print("hello")
永久回圈
uj5u.com熱心網友回復:
用 datetimeimport datetime
instant = -1 #這個變數用來確保 只列印一次在一個間隔內
while True:
now = datetime.datetime.now()
if now.minute % 5 == 0 and now.minute != instant:
instant = now.minute
print("Hello, world")
uj5u.com熱心網友回復:
CPU使用的太高了
uj5u.com熱心網友回復:
from threading import Timer定時器, 每分鐘探一下時間。
完美一點的話, 就開2個定時器, 第一個是計算下一個時間(0,5,10)的時間差,啟動第二個定時器。 第二個才是作業,設定為5分鐘(300秒)一次。
uj5u.com熱心網友回復:
那就:
1. 加一個time.sleep() , 再測測。 不過這種回圈定時很naive的

import datetime, time
instant = -1
now = datetime.datetime.now()
time.sleep(300 - (now.minute % 5) * 60 - now.second - 1)
while True:
now = datetime.datetime.now()
if now.minute % 5 == 0 and now.minute != instant:
instant = now.minute
print(now.hour, ":", now.minute, ":", now.second)
print("Hello, world")
time.sleep(299)
2. 如樓上 所言, 開個執行緒,定時器定時, 不用回圈
import threading, datetime
def doItRepeatly():
threading.Timer(300, doItRepeatly).start()
print("Hello world")
now = datetime.datetime.now()
first = 300 - (now.minute % 5) * 60 - now.second #找第一個點
threading.Timer(first, doItRepeatly).start()
這個你需要監測一下: 1. 執行緒數量,GC應該 自動回收拋棄的舊執行緒的。
2. 堆的使用情況。 自己測測
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/28348.html
上一篇:wxPython問題: 'MouseEvent' object has no attribute 'GetPositionTuple'
