天天看點

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()