Python script to do something at the same time every day

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

我一直在研究 sched模块和 计时器对象,但我不知道如何使用它们来实现这一点。

344825 次浏览

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/

您只需将其构建到正在调度的函数中,就可以让它调度另一个运行。

你可以这样做:

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)。

EDIT:

正如@PaulMag 所建议的那样,更一般地说,为了查明是否由于到达月底而必须重新设定月份的日期,在这种情况下 y 的定义应当如下:

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

通过此修复程序,还需要向导入添加 timedelta。其他代码行维护相同的。因此,完整的解决方案(同时使用 total _ second ()函数)是:

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()

I spent quite a bit of time also looking to launch a simple Python program at 01:00. For some reason, I couldn't get Cron to launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.

你必须安装他们的 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 &

重启的时候别忘了重启。

我需要类似的东西来完成一项任务,这是我写的代码: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt


def my_job():
print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()