2013-02-26 27 views
31

我有一個長時間運行的python腳本,我想在每天早晨的01:00做些什麼。Python腳本每天在同一時間做點什麼

我一直在尋找sched模塊和Timer對象,但我看不到如何使用它們來實現這一目標。

+6

另請考慮通過[cron](http://en.wikipedia.org/wiki/Cron)運行單獨的腳本。 – FakeRainBrigand 2013-02-26 13:30:20

+0

是的,應該說,不能訪問'cron'。 – 2013-02-26 14:22:38

回答

32

可以是這樣做的:

from datetime import datetime 
from threading import Timer 

x=datetime.today() 
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0) 
delta_t=y-x 

secs=delta_t.seconds+1 

def hello_world(): 
    print "hello world" 
    #... 

t = Timer(secs, hello_world) 
t.start() 

這將在上午01時在第二天執行的功能(例如程序hello_world。)

+1

我需要這樣做*每個*早上... – 2013-02-26 14:02:57

+1

回調可以在第一次調用時啓動另一個「Timer」。 – FakeRainBrigand 2013-02-26 14:31:45

+5

修復日期邏輯:x = datetime.today() y =(x + timedelta(days = 1))。replace(hour = 2,minute = 0,second = 0) delta_t = y - x – 2013-03-01 13:45:21

11

APScheduler可能就是你以後的樣子。

from datetime import date 
from apscheduler.scheduler import Scheduler 

# Start the scheduler 
sched = Scheduler() 
sched.start() 

# Define the function that is to be executed 
def my_job(text): 
    print text 

# The job will be executed on November 6th, 2009 
exec_date = date(2009, 11, 6) 

# Store the job in a variable in case we want to cancel it 
job = sched.add_date_job(my_job, exec_date, ['text']) 

# The job will be executed on November 6th, 2009 at 16:30:05 
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text']) 

https://apscheduler.readthedocs.io/en/latest/

你可以得到它通過建立到正在計劃的功能來安排另一個運行。

+0

這對於apscheduler的第3版不起作用。有沒有人知道與當前的語法類似的例子,我有問題http://stackoverflow.com/q/30280203/2327821 – Michael 2015-05-16 20:18:17

+0

鏈接不工作了 – aaa 2017-06-21 14:15:28

+0

不適用於python 3 – Anarach 2017-06-27 13:18:13

47

我花了不少時間在01:00開始一個簡單的Python程序。出於某種原因,我無法獲得cron來啓動它,而APScheduler似乎相當複雜,應該很簡單。附表(https://pypi.python.org/pypi/schedule)似乎是正確的。

您必須安裝自己的Python庫:

pip install schedule 

這是從他們的樣本程序修改:

import schedule 
import time 

def job(t): 
    print "I'm working...", t 
    return 

schedule.every().day.at("01:00").do(job,'It is 01:00') 

while True: 
    schedule.run_pending() 
    time.sleep(60) # wait one minute 

你需要把自己的功能到位工作,並運行它nohup,例如:

nohup python2.7 MyScheduledProgram.py & 

如果重新啓動,請不要忘記重新啓動它。

+3

任何人在將來都會看到這個主題,希望他們明白這是生產代碼的正確解決方案,而不是公認的方法。 – yeaske 2017-12-20 20:20:49

+0

這會在Mac,Linux和Windows上工作嗎?或者這個腳本需要修改? @yeaske – ppmakeitcount 2018-03-05 03:49:31

+0

我在linux上使用它,它應該在Mac上工作。 Windows,我不確定。然而,設置並仔細測試並不是很好的投資。我會建議,無論如何,因爲調度程序有點棘手。 – user2099484 2018-03-06 08:27:54

5

我需要類似的任務。這是我寫的代碼: 它計算第二天,並將時間更改爲所需的任何時間,並在當前時間和下一個計劃時間之間找到秒數。

import datetime as dt 

def my_job(): 
    print "hello world" 
nextDay = dt.datetime.now() + dt.timedelta(days=1) 
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00" 
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S') 
delay = (newDate - dt.datetime.now()).total_seconds() 
Timer(delay,my_job,()).start() 
相關問題