Расписание Python для запуска функции в определенный день между периодами времени - PullRequest
0 голосов
/ 14 декабря 2018

У меня есть функция, которая обращается к API для проверки данных поезда в определенное время.На самом деле это выполняется 3 раза для каждой поездки, поэтому мне нужно запускать каждую из 3 в определенное время.

Я попытался использовать модуль расписания, чтобы начать работу, но не могузаставить его работать.Вот мой текущий код:

schedule.every().day.at("07:30").every(5).minutes.do(darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time']))

Но я получаю AttributeError: у объекта 'Job' нет атрибута 'each'.В документации говорится, что это происходит, если ваш код импортирует неправильный модуль расписания, но у меня нет других файлов с таким именем.

Как бы я выполнил свою функцию, скажем, каждую пятницу с 07:30 до 08: 40, каждые 5 минут?

Редактировать: В соответствии с запросом, добавил мой полный код для того, что я пытаюсь сделать:

import requests
import re
import schedule
import time
from darwin_token import DARWIN_KEY

jsonToken = DARWIN_KEY

train_station = {'work_station': 'bat', 'home_station': 'man', 'connect_station': 'wds'}
user_time = {'morning_time': ['0821', '0853'], 'evening_time': ['1733'], 'connect_time': ['0834', '0843']}


def darwinChecker(departure_station, arrival_station, user_time):
response = requests.get("https://huxley.apphb.com/all/" + str(departure_station) + "/to/" + str(arrival_station) + "/" + str(user_time), params={"accessToken": jsonToken})
    response.raise_for_status()    # this makes an error if something failed
data1 = response.json()
train_service = data1["trainServices"]
print('Departure Station: ' + str(data1.get('crs')))
print('Arrival Station: ' + str(data1.get('filtercrs')))
print('-' * 40)
try:
    found_service = 0  # keeps track of services so note is generated if service not in user_time
    for index, service in enumerate(train_service):
        if service['sta'].replace(':', '') in user_time:  # replaces sta time with values in user_time
            found_service += 1  # increments for each service in user_time
            print('Service RSID: ' + str(train_service[index]['rsid']))
            print('Scheduled arrival time: ' + str(train_service[index]['sta']))
            print('Scheduled departure time: ' + str(train_service[index]['std']))
            print('Status: ' + str(train_service[index]['eta']))
            print('-' * 40)
            if service['eta'] == 'Cancelled':
                # print('The ' + str(train_service[index]['sta']) + ' service is cancelled.')
                print('Previous train departure time: ' + str(train_service[index - 1]['sta']))
                print('Previous train status: ' + str(train_service[index - 1]['eta']))
    if found_service == 0:  # if no service is found
        print('The services currently available are not specified in user_time.')
except TypeError:
    print('There is no train service data')
try:
    # print('\nNRCC Messages: ' + str(data1['nrccMessages'][0]['value']))
    NRCCRegex = re.compile('^(.*?)[\.!\?](?:\s|$)')  # regex pulls all characters until hitting a . or ! or ?
    myline = NRCCRegex.search(data1['nrccMessages'][0]['value'])  # regex searches through nrccMessages
    print('\nNRCC Messages: ' + myline.group(1))  # prints parsed NRCC message
except (TypeError, AttributeError) as error:  # tuple catches multiple errors, AttributeError for None value
    print('There is no NRCC data currently available\n')


print('Morning Journey'.center(50, '='))
darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time'])
# schedule.every().day.at("21:50").do()
# schedule.every(2).seconds.do(darwinChecker,train_station['home_station'], train_station['connect_station'], user_time['morning_time'])     

schedule.every().day.at("07:30").every(5).minutes.do(darwinChecker,train_station['home_station'], train_station['connect_station'], user_time['morning_time'])

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

# print('Connection Journey'.center(50, '='))
# darwinChecker(train_station['connect_station'], train_station['work_station'], user_time['connect_time'])

# print('Evening Journey'.center(50, '='))
# darwinChecker(train_station['work_station'], train_station['home_station'], user_time['evening_time'])`
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...