Skip to content

Commit ef87b84

Browse files
committed
add py_schedule.py
1 parent fab50b2 commit ef87b84

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

python_schedule.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
调度的使用
5+
"""
6+
7+
import time
8+
import datetime
9+
from threading import Timer
10+
from apscheduler.schedulers.blocking import BlockingScheduler
11+
from apscheduler.schedulers.background import BackgroundScheduler
12+
13+
14+
def print_hello():
15+
print("TimeNow in func: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
16+
return
17+
18+
19+
if __name__ == "__main__":
20+
# 1. 使用Threading模块中的Timer
21+
# t = Timer(2, print_hello)
22+
#
23+
# print("TimeNow start: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
24+
# t.start()
25+
# print("TimeNow end: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
26+
# exit()
27+
28+
# 2. BlockingScheduler:在进程中运行单个任务,调度器是唯一运行的东西, 采用阻塞的方式
29+
scheduler = BlockingScheduler()
30+
31+
# 采用固定时间间隔(interval)的方式,每隔5秒钟执行一次
32+
scheduler.add_job(print_hello, "interval", seconds=5)
33+
34+
# 采用date的方式,在特定时间只执行一次
35+
# scheduler.add_job(print_hello, "date", run_date=datetime.datetime.now() + datetime.timedelta(seconds=5))
36+
37+
# print("TimeNow start: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
38+
# scheduler.start()
39+
# print("TimeNow end: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
40+
# exit()
41+
42+
# 3. BackgroundScheduler: 适合于要求任何在程序后台运行的情况,当希望调度器在应用后台执行时使用。采用非阻塞的方式
43+
scheduler = BackgroundScheduler()
44+
45+
# 采用固定时间间隔(interval)的方式,每隔3秒钟执行一次
46+
scheduler.add_job(print_hello, "interval", seconds=5)
47+
48+
# 这是一个独立的线程
49+
# print("TimeNow start: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
50+
# scheduler.start()
51+
# print("TimeNow end: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
52+
# while True:
53+
# time.sleep(2)

0 commit comments

Comments
 (0)