如何在特定时间运行Python脚本

15

我想为完成一个特定的任务编写一个简单的Python脚本。我正在从一个网站获取一些时间和链接信息。

times=
[
('17.04.2011', '06:41:44', 'abc.php?xxx'),
('17.04.2011', '07:21:31', 'abc.php?yyy'),
('17.04.2011', '07:33:04', 'abc.php?zzz'),
('17.04.2011', '07:41:23', 'abc.php?www'),]

如何在正确的时间点击这些链接?我需要计算当前时间和列表中下一个时间间隔,并休眠一段时间吗?

我真的卡在这一点上了,欢迎任何有用的想法。


可能是Python定时脚本的重复问题。 - user2665694
dupe of https://dev59.com/3FbTa4cB1Zd3GeqP8jMh#5658088 - user2665694
4个回答

11

看一下Python的sched模块。


8

您可以使用计划模块,它易于使用且能够满足您的要求。

您可以尝试以下内容。

import datetime, schedule, requests, time

TIME = [('17.04.2011', '06:41:44', 'abc.php?xxx'),
    ('17.04.2011', '07:21:31', 'abc.php?yyy'),
    ('17.04.2011', '07:33:04', 'abc.php?zzz'),
    ('17.04.2011', '07:41:23', 'abc.php?www')]

def job():
    global TIME
    date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
    for i in TIME:
        runTime = i[0] + " " + i[1]
        if i and date == str(runTime):
            requests.get(str(i[2]))

schedule.every(0.01).minutes.do(job)

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

我使用request模块和get方法调用这些URL。您可以编写适合您的任何方法。

这是一个很好的例子! - William
1
顺便提一下,您不需要使用 global TIME,因为代码中没有重新分配 TIME - Was'

3

1

我终于做出来并且使用了这个。

import time,datetime

def sleep_till_future(f_minute):
    """The function takes the current time, and calculates for how many seconds should sleep until a user provided minute in the future."""       
    t = datetime.datetime.today()
    future = datetime.datetime(t.year,t.month,t.day,t.hour,f_minute)
    if future.minute <= t.minute:
        print("ERROR! Enter a valid minute in the future.")
    else:
        print "Current time: " + str(t.hour)+":"+str(t.minute)
        print "Sleep until : " + str(future.hour)+":"+str(future.minute)
        seconds_till_future = (future-t).seconds
        time.sleep( seconds_till_future )
        print "I slept for "+str(seconds_till_future)+" seconds!"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接