2011-04-15 107 views
9

我想寫一個簡單的python腳本來完成特定的工作。我從網站上獲得一些時間和鏈接信息。如何在特定時間運行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'),] 

什麼是在正確的時間點擊這些鏈接的最佳方式?我是否需要計算當前和列表中的時間間隔並睡一會兒?

我真的被困在這一點,並開放給任何可能有用的想法。

+0

[Python的定時腳本](http://stackoverflow.com/questions/5657429/python-timed-script) – 2011-04-15 14:01:47

+0

欺騙的可能重複http://stackoverflow.com/questions/5657429/python-timed-腳本/ 5658088#5658088 – 2011-04-15 14:01:55

回答

8

看看Python的sched模塊。

3

This可能會有所幫助。它關於Python中類似於cron的調度。是的,它基於睡眠。

1

我終於做出並使用了這個。

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. 
    """ 
    import time,datetime 


    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!" 
3

您可以使用調度模塊,它是易於使用,將滿足您的要求。

你可以嘗試這樣的事情。

import datetime, schedule, request 

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): 
      request.get(str(i[2])) 

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

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

我使用請求模塊和get方法調用這些URL。你可以寫出適合你的任何方法。