Python脚本每天在同一时间做一些事情

2024-03-29 07:02:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 模块对象脚本时间事情timersched
3条回答

我花了很多时间在01:00启动一个简单的Python程序。出于某种原因,我无法让cron启动它,而APScheduler对于一些应该很简单的事情来说似乎相当复杂。日程安排(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 &

如果重新启动,不要忘记重新启动。

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)

编辑:

正如@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()

相关问题 更多 >