本文目录导读:

- Linux/macOS 系统:Cron 定时任务
- Python 自建定时器
- Windows 系统:任务计划程序
- Python 使用 threading + Timer
- APScheduler 高级调度
- Node.js 定时任务
- 实用技巧
- 推荐选择
Linux/macOS 系统:Cron 定时任务
添加定时任务
# 编辑 crontab crontab -e # 格式:分 时 日 月 周 命令 # 每天凌晨2点执行 0 2 * * * /path/to/script.sh # 每30分钟执行 */30 * * * * /path/to/script.sh # 每天上午8点到下午6点,每2小时执行 0 8-18/2 * * * /path/to/script.sh
Python 示例(保存为 script.py)
#!/usr/bin/env python3
import subprocess
import sys
def main():
# 你的定时任务代码
print("定时任务执行了!")
# 执行其他命令
subprocess.run(["ls", "-la"])
if __name__ == "__main__":
main()
Python 自建定时器
import time
import schedule
def job():
print("定时任务执行中...")
# 每10秒执行一次
schedule.every(10).seconds.do(job)
# 每天上午10:30执行
schedule.every().day.at("10:30").do(job)
# 每周一执行
schedule.every().monday.do(job)
while True:
schedule.run_pending()
time.sleep(1)
Windows 系统:任务计划程序
PowerShell 添加定时任务
# 创建每天执行的任务 $action = New-ScheduledTaskAction -Execute "python.exe" -Argument "C:\script\my_script.py" $trigger = New-ScheduledTaskTrigger -Daily -At "09:00" Register-ScheduledTask -TaskName "MyDailyTask" -Action $action -Trigger $trigger
或使用 schtasks 命令
# 每天9点运行 schtasks /create /tn "MyTask" /tr "python C:\script.py" /sc daily /st 09:00
Python 使用 threading + Timer
import threading
import time
def repeat_task(interval):
"""定时重复执行"""
def wrapper():
repeat_task(interval) # 重新设定定时器
print(f"{time.strftime('%H:%M:%S')} - 执行任务")
# 这里放你的任务代码
timer = threading.Timer(interval, wrapper)
timer.daemon = True
timer.start()
# 每5秒执行一次
repeat_task(5)
# 保持程序运行
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("程序退出")
APScheduler 高级调度
from apscheduler.schedulers.blocking import BlockingScheduler
def my_job():
print(f"任务执行: {time.strftime('%Y-%m-%d %H:%M:%S')}")
scheduler = BlockingScheduler()
# cron 表达式
scheduler.add_job(my_job, 'cron', day_of_week='mon-fri', hour=9, minute=30)
# 间隔执行
scheduler.add_job(my_job, 'interval', minutes=30)
# 单次定时
scheduler.add_job(my_job, 'date', run_date='2024-01-01 00:00:00')
scheduler.start()
Node.js 定时任务
// 安装: npm install node-cron
const cron = require('node-cron');
// 每天凌晨3点执行
cron.schedule('0 3 * * *', () => {
console.log('执行定时任务');
});
// 每5分钟执行
cron.schedule('*/5 * * * *', () => {
console.log('每5分钟执行一次');
});
// 每月1号执行
cron.schedule('0 0 1 * *', () => {
console.log('每月1号执行');
});
实用技巧
日志记录
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
filename='cron.log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
def job():
try:
# 任务代码
logging.info("任务执行成功")
except Exception as e:
logging.error(f"任务执行失败: {e}")
处理长任务
import subprocess
import os
# 防止任务重叠
lock_file = '/tmp/mylock.lock'
def safe_job():
if os.path.exists(lock_file):
print("上一个任务还在执行,跳过")
return
try:
# 创建锁文件
with open(lock_file, 'w') as f:
f.write(str(os.getpid()))
# 执行长时间任务
subprocess.run(['python', 'long_task.py'])
finally:
# 删除锁文件
if os.path.exists(lock_file):
os.remove(lock_file)
推荐选择
- 简单任务:Cron(Linux)/ 任务计划程序(Windows)
- 需要代码控制:Python schedule 库
- 复杂调度需求:APScheduler
- 跨平台:Python 脚本配合操作系统定时器
需要我详细讲解其中某个方法吗?