日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python定時任務sched庫用法簡單實例_python

作者:IT之一小佬 ? 更新時間: 2023-02-27 編程語言

前言

sched是Python的內置模塊,用于事件調度,可在安全的在多線程環境中輕松實現定時任務。

sched是一種調度(延時處理機制)。

sched是python內置庫,不需要安裝。

示例代碼:

import sched
import time
from datetime import datetime
 
# 初始化sched模塊的scheduler類
# 第一個參數是一個可以返回時間戳的函數,第二個參數可以在定時未到達之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)
 
def task(inc):
    now = datetime.now()
    ts = now.strftime("%Y-%m-%d %H:%M:%S")
    print(ts)
    schedule.enter(inc, 0, task, (inc,))
 
def func(inc=3):
    # enter四個參數分別為:
    # 間隔事件、優先級(用于同時間到達的兩個事件同時執行時定序)、被調用觸發的函數、給該觸發函數的參數(tuple形式)
    schedule.enter(0, 0, task, (inc,))
    schedule.run()
 
func()

運行結果:

補充:解析

主要使用調度器對象 sched.scheduler

調度器對象初始化方法 def __init__(self, timefunc=_time, delayfunc=time.sleep)

  • timefunc:經過時間調用的方法,默認為 time.monotonic(),返回單調時鐘的值,單位為小數秒
  • delayfunc:延遲時間調用的方法,默認為 time.sleep(secs),線程暫停執行secs秒

調度器對象方法和屬性有:

方法或屬性 功能
scheduler.enterabs(time, priority, action, argument=(), kwargs={}) 安排一個新事件
scheduler.enter(delay, priority, action, argument=(), kwargs={}) 安排延后 delay 時間單位的事件
scheduler.cancel(event) 從隊列中刪除事件
scheduler.empty() 判斷事件隊列是否為空
scheduler.run(blocking=True) 運行所有預定事件
scheduler.queue 按運行順序返回事件列表

總結?

原文鏈接:https://blog.csdn.net/weixin_44799217/article/details/127353545

欄目分類
最近更新