1
头图

前提条件:
安装了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()

城中月
7 声望4 粉丝