python几种定时器使用及示例

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')

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')

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
  • 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() 

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() 
  • 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()

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() 
  • 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()

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()

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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中,有几种方法可以使用定时器。 第一种方法是使用`time`模块。你可以使用`time.sleep()`函数来实现简单的定时器功能。例如,如果你想要在2秒后执行某个函数,你可以使用`time.sleep(2)`来暂停程序的执行,然后再调用该函数。这种方法适用于简单的定时任务。 第二种方法是使用`threading`模块。你可以创建一个`Timer`对象,并指定定时器的间隔时间和要执行的函数。例如,你可以使用`threading.Timer(2, func)`来创建一个2秒后执行`func`函数的定时器。然后,你可以使用`timer.start()`来启动定时器。这种方法适用于需要循环调用的定时任务。 第三种方法是使用`schedule`模块。`schedule`是一个轻量级的定时任务调度库。你可以使用`schedule.every().day.at("03:00").do(func)`来创建一个每天在3点执行`func`函数的定时任务。这种方法适用于复杂的定时任务。 另外,如果你在使用`crontab`执行Python脚本时遇到了版本问题,你可以在`crontab`中指定Python解释器的路径。你可以使用`whereis python`命令来查找Python 2.7版本的路径。 综上所述,这是使用定时器几种方法。你可以根据你的需求选择适合的方法来实现定时任务。 #### 引用[.reference_title] - *1* [树莓派Python3 使用定时器](https://blog.csdn.net/qq_35831134/article/details/89681202)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [python实现定时器](https://blog.csdn.net/weixin_45459224/article/details/102600181)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Python-定时器使用](https://blog.csdn.net/weixin_39730587/article/details/110959945)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值