python定時任務之小試牛刀

城中月發表於2024-11-25

前提條件:
安裝了apscheduler

定時任務demo1
timed_task.py

import time

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta

# 定義一個任務
def timed_task():
    # 列印目前時間
    utc_time = datetime.utcnow()
    beijing_time = utc_time + timedelta(hours=8)
    print(beijing_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3])

# 定義一個排程器scheduler
scheduler = BackgroundScheduler()
# 使用scheduler設定一個定時任務:每間隔2秒執行一次timed_task函式
scheduler.add_job(timed_task, 'interval', seconds=2)
# 啟動定時任務
scheduler.start()

try:
    while True:
        time.sleep(5)
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()

定時任務demo2
multi_timed_tasks.py

import time
from datetime import datetime, timedelta

from apscheduler.schedulers.background import BackgroundScheduler

def get_beijing_time():
    # 返回北京時間
    utc_time = datetime.utcnow()
    beijing_time = utc_time + timedelta(hours=8)
    return beijing_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

def task1():
    print('task1 is eating!' + get_beijing_time())

def task2():
    print('task2 is drinking!' + get_beijing_time())

scheduler = BackgroundScheduler()
scheduler.add_job(task1, 'interval', seconds=2)
scheduler.add_job(task2, 'interval', seconds=5)

scheduler.start()

try:
    while True:
        time.sleep(12)
except Exception:
    scheduler.shutdown()

定時任務demo3
timed_file.py
前提條件:
1.已經掌握python os模組中常見操作
2.在timed_file.py所在目錄下已經新建了名為dirs的目錄

import os
import time
from datetime import datetime, timedelta

from apscheduler.schedulers.background import BackgroundScheduler

def get_beijing_time():
    # 返回北京時間
    utc_time = datetime.utcnow()
    beijing_time = utc_time + timedelta(hours=8)
    return beijing_time.strftime("%Y-%m-%d-%H-%M-%S-%f")[:-3]

def create_dir():
    dir_name = get_beijing_time()
    dir_path = os.path.join(os.path.abspath('.'),'dirs',dir_name)
    os.mkdir(dir_path, mode=0o777)

def count_fir_number():
    dir_path = os.path.join(os.path.abspath('.'), 'dirs')
    num = len(os.listdir(dir_path))
    print(f'there is {num} dirs!')

scheduler = BackgroundScheduler()
scheduler.add_job(create_dir, 'interval', seconds=5)
scheduler.add_job(count_fir_number, 'interval', seconds=3)

scheduler.start()

try:
    while True:
        time.sleep(12)
except Exception:
    scheduler.shutdown()

相關文章