簡體   English   中英

Python:執行時間

[英]Python: Time of day to execute

我寫了一個小腳本來獲取即時股票價格。

#script to get stock data

from __future__ import print_function
import urllib
import lxml.html
from datetime import datetime
import sys
import time

stocks=["stock1","stock2","stock3","stock4","stock5"]

while True:
 f=open('./out.txt', 'a+')
 for x in stock:
  url = "http://someurltofetchdata/"+x
  code   = urllib.urlopen(url).read()
  html   = lxml.html.fromstring(code)
  result = html.xpath('//td[@class="LastValue"][position() = 1]')
  result = [el.text_content() for el in result]
  f.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' ' + x + ' ' + result[0])
  f.write("\n")
 f.close()

我希望該代碼僅在股票市場開放的幾小時內獲取數據,這意味着交易時間。 (09:00至12:30和13:30至17:30)。

你能否建議一種隱含在代碼上執行調度的方法? (不在操作系統級別)

如果您不能使用cron(這是完成任務的最簡單方法),您可以將其添加到您的代碼中。 如果在給定的時間范圍內,它將下載數據,睡眠60秒然后再次運行。

while True:
    now = datetime.now().strftime('%H%M')
    if '0900' <= now <= '1230' or '1330' <= now <= '1730':
        # your code starting with f=open('./out.txt', 'a+')
    time.sleep(60)

看看APScheduler

from apscheduler.scheduler import Scheduler
sched = Scheduler()

@sched.interval_schedule(hours=3)
def some_job():
    print "Decorated job"

sched.configure(options_from_ini_file)
sched.start()

您還可以指定time.date

job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

顯然你必須編寫一些代碼來在相關時間打開和關閉sched.start() sched.stop() ,但隨后它會自動獲取你在裝飾器上設置的數據。 你甚至可以安排時間表!

如果要在Windows上安排此腳本,請使用任務計划 在此輸入圖像描述 它具有GUI配置,非常簡單。 對於Linux,crontab會更好。 最重要的是,您不需要修改代碼,並且長期運行也非常穩定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM