首页 后端开发 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

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

PHP教程
1596
276
如何在Sublime文本中调试Python代码? 如何在Sublime文本中调试Python代码? Aug 14, 2025 pm 04:51 PM

UseSublimeText’sbuildsystemtorunPythonscriptsandcatcherrorsbypressingCtrl Baftersettingthecorrectbuildsystemorcreatingacustomone.2.Insertstrategicprint()statementstocheckvariablevalues,types,andexecutionflow,usinglabelsandrepr()forclarity.3.Installth

如何在Sublime文本中运行Python代码? 如何在Sublime文本中运行Python代码? Aug 16, 2025 am 04:58 AM

确保已安装Python并将其添加到系统PATH,通过终端运行python--version或python3--version验证;2.将Python文件保存为.py扩展名,如hello.py;3.在SublimeText中创建自定义构建系统,Windows用户使用{"cmd":["python","-u","$file"]},macOS/Linux用户使用{"cmd":["python3

如何在VScode中调试Python脚本 如何在VScode中调试Python脚本 Aug 16, 2025 am 02:53 AM

要调试Python脚本,需先安装Python扩展并配置解释器,然后创建launch.json文件设置调试配置,接着在代码中设置断点并按F5启动调试,脚本将在断点处暂停,允许检查变量和单步执行,最终通过查看控制台输出、添加日志或调整参数等方式排查问题,确保环境正确后调试过程简单高效。

如何在VSCODE中自动格式化Python代码 如何在VSCODE中自动格式化Python代码 Aug 14, 2025 pm 04:10 PM

toAutomation formatemationalformatpytpythoncodeinvscode,installblackusingpipinstallblack,installtheofficialmicrosoftpythonextension,setblackastheformatterinsettings.jsonwith“ python.formatting.formatting.provider”

Python中的类方法是什么 Python中的类方法是什么 Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

收益率关键字如何在Python中起作用 收益率关键字如何在Python中起作用 Aug 15, 2025 am 08:23 AM

yield关键字用于定义生成器函数,使其能暂停执行并逐个返回值,之后从暂停处恢复;生成器函数返回生成器对象,具有惰性求值特性,可节省内存,适用于处理大文件、流数据和无限序列等场景,且生成器是迭代器,支持next()和for循环,但无法倒回,必须重新创建才能再次迭代。

python asyncio队列示例 python asyncio队列示例 Aug 21, 2025 am 02:13 AM

asyncio.Queue是用于异步任务间安全通信的队列工具,1.生产者通过awaitqueue.put(item)添加数据,消费者用awaitqueue.get()获取数据;2.每处理完一项需调用queue.task_done(),以便queue.join()等待所有任务完成;3.使用None作为结束信号通知消费者停止;4.多个消费者时,需发送多个结束信号或在取消任务前确保所有任务已处理完毕;5.队列支持设置maxsize限制容量,put和get操作自动挂起不阻塞事件循环,程序最终通过canc

如何在Sublime文本中创建一个Python项目? 如何在Sublime文本中创建一个Python项目? Aug 16, 2025 am 08:53 AM

InstallSublimeTextandPython,thenconfigureabuildsystembycreatingaPython3.sublime-buildfilewiththeappropriatecmdandselectorsettingstoenablerunningPythonscriptsviaCtrl B.2.OrganizeyourprojectbycreatingadedicatedfolderwithPythonfilesandsupportingdocument

See all articles