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

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

本文介绍了每天在同一时间做某事的Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我一直在查看 sched 模块和Timer 对象,但我不知道如何使用这些实现这一目标.

I have been looking at the sched module and at the Timer object but I can't see how to use these to achieve 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()

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

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

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

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:

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

通过此修复,还需要将 timedelta 添加到导入中.其他代码行保持相同.因此,还使用 ​​total_seconds() 函数的完整解决方案是:

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:

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

这篇关于每天在同一时间做某事的Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 17:41