要让Python程序每天自动执行,你可以使用以下几种方法:
方法一:使用Windows任务计划程序
1. 打开“任务计划程序”(在Windows搜索栏中输入“任务计划程序”)。
2. 点击“创建基本任务”按钮,输入任务名称并按照向导步骤完成设置。
3. 在“操作”选项卡中,选择“启动程序”。
4. 设置程序或脚本,这里以运行Python为例,输入“python.exe”。
5. 添加参数,这里我们选择需要运行的Python文件路径。
6. 在“触发器”选项卡中,选择“新建”,然后设置运行该任务的时间和日期。
7. 点击“确定”按钮,保存您的任务。
方法二:使用Python内置模块`sched`
import sched
import time
def job():
print("I'm working...")
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(60, 1, job) 每隔60秒执行一次job函数
scheduler.enter(3600, 1, job) 每隔3600秒(1小时)执行一次job函数
scheduler.enter(86400, 1, job) 每天在特定时间执行job函数
while True:
scheduler.run_pending()
time.sleep(1)
方法三:使用第三方库`Timeloop`
from timeloop import Timeloop
def job():
print("I'm working...")
tl = Timeloop()
tl.add_interval(10, job) 每隔10秒执行一次job函数
tl.start()
方法四:使用`while True: + sleep()`循环
import time
while True:
time.sleep(86400) 暂停86400秒(24小时)
job() 执行任务
方法五:使用`threading.Timer`
import threading
import time
def job():
print("I'm working...")
threading.Timer(86400, job).start() 每隔86400秒(24小时)执行一次job函数
threading.Timer(86400, job).start()
选择适合你需求的方法进行设置,确保你的Python程序能够在每天指定的时间自动执行。