[英]Run the script every X minute
I want this script to run every minute... 我希望此脚本每分钟运行一次...
import time
import urllib2
from time import sleep
stocksToPull = str('1101'),str('1102'),str('1201'),str('1216'),str('1227')
def pullData(stock):
try:
fileLine = stock+'.txt'
urlToVisit = 'http://mis.tse.com.tw/data/'+stock+'.csv'
sourceCode = urllib2.urlopen(urlToVisit).read()
splitSource = sourceCode.split('\n')
for everyLine in splitSource:
splitLine = everyLine.split(',')
if len(splitLine)==40:
saveFile = open(fileLine,'a')
everyLine = everyLine.replace('"','')
lineToWrite = everyLine+'\n'
saveFile.write(lineToWrite)
print 'pulled',stock
print 'sleeping.....'
except Exception,e:
print ',main loop',str(e)
for eachStock in stocksToPull:
pullData(eachStock)
while True:
starttime = time.time()
pullData(eachStock)
endtime = time.time()-starttime
sleep(65-endtime)
and I run this,it's work. 我运行它,它正在工作。 It will gets the data of eachstock at the first time but after 1 minute later it just pull '1227''s data, it wont pull all of them. 它会在第一时间获取每种股票的数据,但是在一分钟后,它只会提取'1227'的数据,而不会提取所有数据。 It looks like this: 看起来像这样:
pulled 1101
sleeping.....
pulled 1102
sleeping.....
pulled 1201
sleeping.....
pulled 1216
sleeping.....
pulled 1227
sleeping.....
pulled 1227
sleeping.....
pulled 1227
sleeping.....
How could solve this problem? 如何解决这个问题? I use python 2.7. 我使用python 2.7。
I think you really mean to do this: 我认为您真的是想这样做:
while True:
starttime = time.time()
for eachStock in stocksToPull:
pullData(eachStock)
duration = time.time()-starttime
sleep(65-duration)
I assume you are calculating the sleep time because you want it to run exactly 65 seconds apart, regardless of how long it took to pullData() for each stock. 我假设您正在计算睡眠时间,因为您希望它每隔65秒运行一次,而不管每种股票对pullData()花费多长时间。 You can use APScheduler to do something like this with an interval schedule. 您可以使用APScheduler通过间隔计划执行类似的操作。 They have nice decorators, too. 他们也有漂亮的装饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.