每天在同一时间做某事的 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15088037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:18:31  来源:igfitidea点击:

Python script to do something at the same time every day

pythonpython-2.7scheduler

提问by Paul McKenzie

I have a long running python script that I want to do someting at 01:00 every morning.

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

I have been looking at the schedmodule and at the Timerobject but I can't see how to use these to achieve this.

我一直在查看sched模块和Timer对象,但我看不到如何使用它们来实现这一目标。

采纳答案by sissi_luaty

You can do that like this:

你可以这样做:

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

This will execute a function (eg. hello_world) in the next day at 1a.m.

这将在第二天凌晨 1 点执行一个函数(例如 hello_world)。

EDIT:

编辑:

As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:

正如@PaulMag 所建议的那样,更一般地,为了检测是否由于到达月底而必须重置月份中的日期,在这种情况下 y 的定义应如下所示:

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

With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:

使用此修复程序,还需要将 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()

回答by Paul Collingwood

APScheduler might be what you are after.

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/

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

You can just get it to schedule another run by building that into the function you are scheduling.

您可以通过将其构建到您正在调度的函数中来让它安排另一次运行。

回答by user2099484

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 cronto launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.

我还花了很多时间寻找在 01:00 启动一个简单的 Python 程序。出于某种原因,我无法让cron来启动它,而 APScheduler 对于一些应该很简单的东西来说似乎相当复杂。时间表(https://pypi.python.org/pypi/schedule)似乎是正确的。

You will have to install their Python library:

您必须安装他们的 Python 库:

pip install schedule

This is modified from their sample program:

这是从他们的示例程序中修改的:

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

You will need to put your own function in place of job and run it with nohup, e.g.:

您需要将自己的功能放在工作位置并使用 nohup 运行它,例如:

nohup python2.7 MyScheduledProgram.py &

Don't forget to start it again if you reboot.

如果您重新启动,请不要忘记再次启动它。

回答by Ankit

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

我需要类似的东西来完成任务。这是我写的代码:它计算第二天并将时间更改为所需的任何时间,并在 currentTime 和下一个预定时间之间找到秒数。

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