首页 > 解决方案 > 在python中的特定时间运行函数

问题描述

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

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

标签: pythontimepython-webbrowser

解决方案


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

推荐阅读