【问题标题】:Run function at a specific time in python [duplicate]在python中的特定时间运行函数[重复]
【发布时间】:2018-10-11 18:57:37
【问题描述】:
import time
import webbrowser

print(time.ctime())

targetTime = time.ctime()


if(targetTime == "Tue May 01 11:05:17 2018"):    
    webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

这是我已经尝试过的,到时候它不会打开链接。我通读了时间图书馆,但找不到任何可以帮助我的东西。我的目标是让程序在我想要的时间打开一个链接。任何帮助表示赞赏。

【问题讨论】:

  • 一般来说,编程并不神奇。除非您不断更新时间(并将其与时间而不是字符串进行比较),否则这是行不通的。
  • 我刚刚开始了一个基本的 Python 教程,他使用 time.sleep 来实现同样的目的,但我的问题是我可能不会像昨天一样启动程序,所以会搞砸我起来。这就是我在这里问的原因,因为我想运行该程序,它会在我想要的时间执行我的功能。

标签: python time python-webbrowser


【解决方案1】:

Python 内置了一个名为sched 的简单调度库,支持这一点。

import sched, time

def action():
    webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

# Set up scheduler
s = sched.scheduler(time.localtime, time.sleep)
# Schedule when you want the action to occur
s.enterabs(time.strptime('Tue May 01 11:05:17 2018'), 0, action)
# Block until the action has been run
s.run()

【讨论】:

    【解决方案2】:

    如果你不介意使用第三方模块,有Python pause

    import pause
    from datetime import datetime
    
    pause.until(datetime(2018, 5, 1, 11, 5, 17))
    webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 2010-11-05
      • 2020-10-07
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多