python框架---->APScheduler的使用
这里介绍一下python中关于定时器的一些使用,包括原生的sche包和第三方框架APScheduler的实现。流年未亡,夏日已尽。种花的人变成了看花的人,看花的人变成了葬花的人。
python中的sche模块
python中的sch有模块提供了定时器任务的功能,在3.3版本之后sche模块里面的scheduler类在多线程的环境中是安全的。以下是一个案例
import sched, time
sche = sched.scheduler(time.time, time.sleep)
def print_time(a='default'):
print('From print_time', time.time(), a)
def print_some_time():
print(time.time())
# 10是delay单位是毫秒, 1代表优先级
sche.enter(10, 1, print_time)
sche.enter(5, 2, print_time, argument=('positional',))
sche.enter(5, 1, print_time, kwargs={'a': 'keyword'})
sche.run()
print(time.time())
print_some_time()
运行的打印结果如下:
1511139390.598038
From print_time 1511139395.5982432 keyword
From print_time 1511139395.5982432 positional
From print_time 1511139400.5984359 default
1511139400.5984359
查看scheduler.enter的源码,可以看到它实际调用的是enterabs方法。
def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
"""A variant that specifies the time as a relative time.
This is actually the more commonly used interface.
"""
time = self.timefunc() + delay
return self.enterabs(time, priority, action, argument, kwargs)
而对于enterabs方法的argument和kwargs的含义,官方文档的解释如下:它们可以作为action的参数,也就是上述例子中的print_time方法的参数
argument is a sequence holding the positional arguments for action. kwargs is a dictionary holding the keyword arguments for action.
APScheduler的使用
- APScheduler的安装
pip install apscheduler。
- APScheduler的使用案例
每隔一秒打印出Hello World的字符。
from apscheduler.schedulers.blocking import BlockingScheduler
def my_job():
print('Hello World')
sched = BlockingScheduler()
sched.add_job(my_job, 'interval', seconds=1)
sched.start()
友情链接
- 关于APScheduler的官方文档:https://apscheduler.readthedocs.io/en/latest/userguide.html
作者:
huhx
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。