2018年5月15日火曜日

[python]タイマーで1日3回プログラムを動かす(sleep)

スクレイピングで1日3回データを取りに行きたいときのため

time.sleep()で待たせる
import datetime
import sys
import time
get_data_when_run = True
now = datetime.datetime.now()
now_date = datetime.datetime(now.year, now.month, now.day)
while True:
   
    if 5 <= now.hour < 11:
        delta = datetime.timedelta(hours=11, minutes=15)
    elif 11 <= now.hour < 17:
        delta = datetime.timedelta(hours=17, minutes=15)
    else:
        delta = datetime.timedelta(days=1, hours=5, minutes=15)
    if get_data_when_run:
        start_time = now_date
       
    else:
        start_time = now_date + delta
        print("next start_time", start_time)
        print("wait minutes", round((start_time - datetime.datetime.now()).total_seconds()/60))
        time.sleep((start_time - datetime.datetime.now()).total_seconds())
   
    if get_data_when_run:
        print('get now only beginning', datetime.datetime.today())
        get_data_when_run = False
    else:
        print("interval check", datetime.datetime.today())
   
    ## do something
    print("--do something--")
    ##
    now = datetime.datetime.now()  # next now
    now_date = datetime.datetime(now.year, now.month, now.day)

0 件のコメント:

コメントを投稿