搜尋
首頁後端開發Python教學Python定時器怎麼使用

Python定時器怎麼使用

May 12, 2023 pm 04:43 PM
python

這裡我們開發一個print_datetime函數來列印目前的時間,同時也將print_time函數當作我們需要一直保持執行的任務。

# Importing the datetime module.
import datetime


def print_time(message=None):
    """
    It prints the current time, optionally preceded by a message.

    :param message: The message to print
    """
    print(message, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

然後,我們準備需要使用的定時任務模組apscheduler,可以選擇pip的方式來安裝,我個人一直使用的是這樣方式。

pip install apscheduler

# Importing the BlockingScheduler class from the apscheduler.schedulers.blocking module.
from apscheduler.schedulers.blocking import BlockingScheduler

至此,我們便可以將需要保持一直處於執行狀態的業務函數,也就是這裡的print_datetime函數作為定時中的任務執行。

如此,我們就不用使用while True死循環 sleep的方式來讓任務一直保存在運行形狀了。

# Creating a scheduler object.
scheduler = BlockingScheduler()

# Adding a job to the scheduler.
scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='cron', second='*/1')  # 每秒执行

# Starting the scheduler in a separate thread.
scheduler.start()

最後,直接啟動目前的.py檔就能直接執行定時任務了,運行效果如下。

時間列印定時任務 2023-02-26 13:52:52
時間列印定時任務 2023-02-26 13:52:53
時間列印定時任務 2023-02 -26 13:52:54
時間列印定時任務 2023-02-26 13:52:55
時間列印定時任務 2023-02-26 13:52:56
#時間列印定時任務 2023- 02-26 13:52:57

當然,作為定時任務的架構apscheduler,他還有很多的技能。例如:按更複雜的周期執行,在有限的時間內執行,單點執行等等。

以下是我列出的比較常見的apscheduler定時任務的執行方式,供小夥伴們參考,提出寶貴意見。

scheduler.add_job(func=print_time, args=('任务只执行一次,在下一次的时间执行',),
                  next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=60))

scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='interval', seconds=5)  # 每5秒执行一次
scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='interval', minutes=2)  # 每2分钟执行一次
scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='interval', hours=1)  # 每1小时执行一次

scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='cron', minute='*', second='1')  # 每分钟执行一次
scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='cron', hour='*', minute='0',
                  second='0')  # 每小时执行一次

scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='cron', hour='20', minute='0',
                  second='0')  # 每天20:00执行一次
scheduler.add_job(func=print_time, args=('时间打印定时任务',), trigger='cron', hour='21')  # 每天21:00执行一次

以上是Python定時器怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

舉一個場景的示例,其中使用Python列表比使用數組更合適。舉一個場景的示例,其中使用Python列表比使用數組更合適。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python數組中訪問元素?您如何在Python數組中訪問元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Apr 28, 2025 pm 04:34 PM

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

Python中的模塊和包裝是什麼?Python中的模塊和包裝是什麼?Apr 28, 2025 pm 04:33 PM

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

Python中的Docstring是什麼?Python中的Docstring是什麼?Apr 28, 2025 pm 04:30 PM

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具