4

我写了一个小脚本来获取即时股票价格。

#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)。

您能否建议一种在代码上隐式执行调度的方法?(不在操作系统级别)

4

3 回答 3

4

如果您不能使用 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)
于 2013-01-03T12:24:01.293 回答
2

看看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(),但是它会按照您在装饰器上设置的频率自动获取数据。你甚至可以安排时间表!

于 2013-01-03T12:44:28.950 回答
0

如果您想在 Windows 上安排此脚本,请使用task schedule在此处输入图像描述。它有 GUI 来配置,而且非常简单。对于 Linux,crontab 会更好。最重要的是,您不需要修改代码,并且长期运行非常稳定。

于 2013-01-03T13:10:39.917 回答