天天看点

Python apscheduler定时任务简单应用

import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler
def func():
    now = datetime.datetime.now()
    ts = now.strftime('%Y-%m-%d %H:%M:%S')
    print('do func time :',ts)
def func2():
    #耗时2S
    now = datetime.datetime.now()
    ts = now.strftime('%Y-%m-%d %H:%M:%S')
    print('do func2 time:',ts)
    time.sleep(2)
def dojob():
     #创建调度器:BlockingScheduler
     scheduler = BlockingScheduler()
     #添加任务,时间间隔2S
     scheduler.add_job(func, 'interval', seconds=2, id='test_job1')
     #添加任务,时间间隔3S
     scheduler.add_job(func2, 'interval', seconds=3, id='test_job2')
     scheduler.start()
dojob()
           
import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler
# from apscheduler.schedulers.blocking import BlockingScheduler
# import datetime
# def halfFunc():
#     
#     print('已过半小时')
#     print(datetime.datetime.now())
#     pass
#
# def clearFunc():
#    
#     print('已过一周')
#     print(datetime.datetime.now())
#     pass
#
# def test():
#     print(datetime.datetime.now())
#     print('test finished')
#
# def test1():
#     print(datetime.datetime.now())
#     print('test1 finished')
#
# def main():
#     # 创建调度器:BlockingScheduler
#     scheduler = BlockingScheduler()
#     # 添加任务,时间间隔半小时
#     #每隔30分钟
#     scheduler.add_job(halfFunc, 'cron', minute='0,30', id='test_job1')
#     # 添加任务,时间间隔一周
#     #星期一0点
#     scheduler.add_job(clearFunc, 'cron', day_of_week=0,hour=0, id='test_job2')
#     #星期三17点
#     scheduler.add_job(test, 'cron', day_of_week=2, hour=17, id='test_job3')
#     #星期三16点58分钟
#     scheduler.add_job(test1, 'cron', day_of_week=2, hour=16,minute=58, id='test_job4')
#     scheduler.start()
#
# if __name__ == '__main__':
#     main()