如何在特定的时间戳时间运行python函数。没有外部软件?

2024-09-28 22:24:29 发布

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

我想告诉python脚本在某个时间戳发生时运行某个函数

我已经寻找了运行时特定的函数 但我找不到任何东西来回答这个具体的问题 计算时间戳

#input is number of days till due date
dueDate = int(input('Days until it is due: '))

#86400 seconds in a day
days = dueDate * 86400

#gets current time stamp time 
currentT = int(time.time())

#gets the timestamp for due date 
alarm = days+currentT

目标是找到python函数,当指定的未来时间戳出现时,该函数可以从脚本中运行另一个函数


Tags: of函数脚本numberinputdatetimeis
3条回答

你可以把剧本睡那么久。你知道吗

time.sleep(alarm)

资料来源:python docs

Schedule是一个很好的python模块。你知道吗

用法:(来自文档)

安装

$ pip install schedule

用法

import schedule
import time

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

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

内置到python中的是sched模块。Here是一篇非常好的文章,而here是官方文档。使用scheduler.enter可以延迟调度,使用scheduler.enterabs可以调度特定的时间。你知道吗

import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def print_event(name):
    print('EVENT:', time.time(), name)

now = time.time()
print('START:', now)

scheduler.enterabs(now+2, 2, print_event, ('first',))
scheduler.enterabs(now+5, 1, print_event, ('second',))

scheduler.run()

输出:

START: 1287924871.34
EVENT: 1287924873.34 first
EVENT: 1287924874.34 second

相关问题 更多 >