【问题标题】:How do i run a python function at a certain timestamp time. Without outside software?我如何在某个时间戳时间运行 python 函数。没有外部软件?
【发布时间】:2019-12-02 04:26:34
【问题描述】:

我想告诉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函数

【问题讨论】:

  • 没有外部软件?你可以使用 pip 安装 python 模块吗?
  • 是的,我可以!你有什么推荐?
  • 请看我的回答。

标签: python function unix timestamp unix-timestamp


【解决方案1】:

你可以让脚本休眠那么久。

time.sleep(alarm)

来源:python docs

【讨论】:

  • 虽然这是功能性的,但从技术上讲,它不是本机调度功能。不幸的是,使用time.sleep() 安排多个任务会很麻烦。
  • 我将此解释为他想要一个内置函数来实现他的目标。我从来没有说过 time.sleep(alarm) 是inferred 请求的理想解决方案。 :)
  • 很公平! :)
【解决方案2】:

构建到 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

【讨论】:

    【解决方案3】:

    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)
    

    【讨论】:

    • 这是24小时的时间
    • schedule.every().day.at("10:30").do(job)
    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2020-04-24
    • 2014-05-20
    • 2019-05-23
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多