Python Schedule模块仅在第一次工作

时间:2018-07-19 01:33:12

标签: python scheduled-tasks scheduler finance

我目前在一家金融公司担任量化实习生。我想做的是让系统每天在16:30将今天的股市数据更新为.csv。

我在线搜索并找到了Schedule模块,这似乎很容易,所以我实现了它。在第一天(星期一),它做得很好,并进行了相应的更新。但是,今天,我检查了服务器昨天(星期二)的日期是否未更新,并且报告了错误。

我如何编写代码如下:

def job():
    stockss = list(all_instruments(type='CS').order_book_id.values)
    for stock in stockss:
    d = datetime.datetime.today().strftime('%Y-%m-%d')
    a = rq.get_price(stock,str(d),str(d))
    df = pd.DataFrame(a)
    with open(str(stock)+'.csv','a') as f:
        df.to_csv(f, header = False)

schedule.every().monday.at("16:30").do(job)
schedule.every().tuesday.at("16:30").do(job)
schedule.every().wednesday.at("16:30").do(job)
schedule.every().thursday.at("16:30").do(job)
schedule.every().friday.at("16:30").do(job)

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

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用另一个功能更强大的模块apscheduler,下面是一个示例:

# ... your import
from apscheduler.schedulers.blocking import BlockingScheduler


def job():
    stockss = list(all_instruments(type='CS').order_book_id.values)
    for stock in stockss:
    d = datetime.datetime.today().strftime('%Y-%m-%d')
    a = rq.get_price(stock,str(d),str(d))
    df = pd.DataFrame(a)
    with open(str(stock)+'.csv','a') as f:
        df.to_csv(f, header = False)


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(job, 'cron', day_of_week="mon-fri", hour="16", minute="30")  # run on Monday to Friday at 16:30
    print('Press Ctrl+C to exit')

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

以下是相关文档:

https://apscheduler.readthedocs.io/en/latest/modules/triggers/cron.html#module-apscheduler.triggers.cron

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