Python脚本每天同一时间执行某任务

130 投票
4 回答
386320 浏览
提问于 2025-04-17 17:10

我有一个长时间运行的Python脚本,我想让它每天早上01:00做一些事情。

我查看了sched模块和Timer对象,但我不知道怎么用这些来实现这个功能。

4 个回答

19

APScheduler可能正是你需要的东西。

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

你可以通过把它放进你要安排的函数里,来让它安排下一次运行。

335

我花了不少时间想要在凌晨1点启动一个简单的Python程序。出于某种原因,我没能让cron来启动它,而APScheduler看起来又太复杂了,感觉不应该这么麻烦。于是我发现Schedule库(https://pypi.python.org/pypi/schedule)挺合适的。

你需要先安装他们的Python库:

pip install schedule

下面的代码是从他们的示例程序修改过来的:

import schedule
import time

def job(t):
    print "I'm working...", t
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

你需要把自己的函数放在job的位置,并用nohup来运行,比如:

nohup python2.7 MyScheduledProgram.py &

如果你重启了电脑,别忘了再启动它。

93

你可以这样做:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

这段代码会在第二天的凌晨1点执行一个函数(比如叫hello_world)。

编辑:

正如@PaulMag建议的那样,更一般地说,为了检测是否需要因为到达月底而重置日期,这里y的定义应该是这样的:

y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)

在这个修正中,还需要将timedelta添加到导入的内容中。其他代码行保持不变。完整的解决方案,同时也使用了total_seconds()函数,因此是:

from datetime import datetime, timedelta
from threading import Timer

x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x

secs=delta_t.total_seconds()

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

撰写回答