当前位置:   article > 正文

python几种定时器使用及示例_qtcore.qtimer()

qtcore.qtimer()

python几种定时器

BlockingScheduler()

from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime

def job():
    print(datetime.now().strtime("%Y-%m-%d %H:%M:%S"))
# BlockingScheduler
scheduler = BlockingScheduler()
scheduler.add_job(job, "cron", day_of_week="1-5", hour=6, minute=30)
scheduler .start()

scheduler.add_job(job, 'cron', hour=1, minute=5)
#hour =19 , minute =23   这里表示每天的19:23 分执行任务
#hour ='19', minute ='23'   这里可以填写数字,也可以填写字符串
#hour ='19-21', minute= '23'   表示 19:23、 20:23、 21:23 各执行一次任务

scheduler .add_job(job, 'interval', seconds=300)#每300秒执行一次

#在1月,3月,5月,7-9月,每天的下午2点,每一分钟执行一次任务
scheduler .add_job(func=job, trigger='cron', month='1,3,5,7-9', day='*', hour='14', minute='*')

# 当前任务会在 6、7、8、11、12 月的第三个周五的 0、1、2、3 点执行
scheduler .add_job(job, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

#从开始时间到结束时间,每隔俩小时运行一次
scheduler .add_job(job, 'interval', hours=2, start_date='2018-01-10 09:30:00', end_date='2018-06-15 11:00:00')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

QTimer()——测试何时执行任务

  • 当本次任务结束,才启动下一次任务执行
  • 不完全按照设置的时间启动任务
from PyQt5.QtCore import QTimer
import time
from PyQt5.QtWidgets import QApplication
import sys
class Update:
    def __init__(self):
        self.t1 = QTimer()
        self.t1.timeout.connect(self.outprint)
        self.t1.start(250)
    def outprint(self):
        status = True
        i = 1
        while status:
            print(i)
            i += 1
            time.sleep(1)
            if i >= 5:
                status = False
if __name__ == '__main__':#不用UI也可以执行,没有下面这几行容易报错
    try:
        app = QApplication(sys.argv)
        refreshvalue = Update()
        sys.exit(app.exec_())
    except KeyboardInterrupt:
        print('\nInterrupted... finishing')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

QtCore.QTimer()

  • core code
t1 = QtCore.QTimer() #Created a QTimer
t1.timeout.connect(outprint) # run def outprint after interval time(1000ms)
t1.start(1000) # run after every 1000ms 
t1.stop() # stop the timer
  • 1
  • 2
  • 3
  • 4
  • example
from PyQt5.QtCore import QTimer
import matplotlib
matplotlib.use("Qt5Agg")  # 声明使用QT5
# from matplotlib.backends.qt_compat import QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure


i = 1
j = 1

def outprint(a = 5):
    global i,j
    if j < a:
        if i < a:
            print("j=",j,"i=",i)
            i += 1
        else:
            t1.stop()
            print("stop")
            j += 1
            i = 1
            print("start")
            t1.start()
    else:
        t1.stop()
        print("stop")
    # print(i)
t1 = QtCore.QTimer()
t1.timeout.connect(outprint)
t1.start(1000)
# t1.stop() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

new_timer(self, interval=None, callbacks=None):

fig.canvas.new_timer

  • core code
import matplotlib.pyplot as plt
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_title, ax)
timer.start()
timer.stop() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • example
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime


i = 1
j = 1

def update_title(axes,a=5):
    axes.set_title(datetime.now())
    axes.figure.canvas.draw()
    global i,j
    if j < a:
        if i < a:
            print("j=",j,"i=",i)
            i += 1
        else:
            timer.stop()
            print("stop")
            j += 1
            i = 1
            print("start")
            timer.start()
    else:
        timer.stop()
        print("stop")

fig, ax = plt.subplots()

x = np.linspace(-3, 3)
ax.plot(x, x ** 2)

# Create a new timer object. Set the interval to 100 milliseconds
# (1000 is default) and tell the timer what function should be called.
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_title, ax)#update_title is func,and ax is come from update_title(ax),property
timer.start()

# Or could start the timer on first figure draw
#def start_timer(evt):
#    timer.start()
#    fig.canvas.mpl_disconnect(drawid)
#drawid = fig.canvas.mpl_connect('draw_event', start_timer)

plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
'
运行

FigureCanvas(Figure()).new_timer

  • core code
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
fg = FigureCanvas(Figure())
t1 = fg.new_timer(interval=100)
t1.add_callback(outprint,a)
t1.start()
t1.stop() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • example
import matplotlib
matplotlib.use("Qt5Agg")  # 声明使用QT5


# from matplotlib.backends.qt_compat import QtCore
from PyQt5.QtCore import QTimer
from PyQt5 import QtCore


from matplotlib.backends.backend_qt5agg import FigureCanvas

from matplotlib.figure import Figure


i = 1
j = 1

def outprint(a = 5):
    global i,j
    if j < a:
        if i < a:
            print("j=",j,"i=",i)
            i += 1
        else:
            t1.stop()
            print("stop")
            j += 1
            i = 1
            print("start")
            t1.start()
    else:
        t1.stop()
        print("stop")

a=7

fg = FigureCanvas(Figure())
t1 = fg.new_timer(interval=100)
t1.add_callback(outprint,a)
t1.start()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

threading.Timer

  1. 定时器构造函数主要有2个参数,第一个参数为时间,第二个参数为函数名,第一个参数表示多长 时间后调用后面第二个参数指明的函数。第二个参数注意是函数对象,进行参数传递,用函数名(如fun_timer)表示该对象,不能写成函数执行语句fun_timer(),不然会报错。用type查看下,可以看出两者的区别。
  2. 必须在定时器执行函数内部重复构造定时器,因为定时器构造后只执行1次,必须循环调用。
  3. 定时器间隔单位是秒,可以是浮点数,如5.5,0.02等,在执行函数fun_timer内部和外部中给的值可以不同。如上例中第一次执行fun_timer是1秒后,后面的都是5.5秒后执行。
  4. 可以使用cancel停止定时器的工作
import threading
import time
def fun_timer():
    print('Hello Timer!')
    global timer
    timer = threading.Timer(5.5, fun_timer)
    timer.start()

timer = threading.Timer(1, fun_timer)
timer.start()

time.sleep(15) # 15秒后停止定时器
timer.cancel()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

QBasicTimer()

self.timer1 = QBasicTimer()
if self.timer1.isActive():
            self.timer1.stop()
            self.btn.setText("开始")
        else:
            self.timer1.start(100, self)
            self.btn.setText("停止")
self.timer1.stop()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号