0

I've got a function that accesses an API to check for train data at specific times. This is actually run 3 times for each journey, so I'd need to run each of the 3 at specific times.

I've tried using the schedule module to get this going but I can't seem to get it working. Here's my current code:

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

But I get an AttributeError: 'Job' object has no attribute 'every'. The documentation states this happens if your code imports the wrong schedule module, but I've no other files under that name.

How would I go about running my function, say, every Friday from 07:30 till 08:40, every 5 minutes?

Edit: As per request, added my full code for what I'm trying to do:

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'])`
Pixxel
  • 71
  • 9
  • What exactly is this Job object. Seems like syntax error. Would help if you show more code. – Adam Dec 13 '18 at 22:38
  • The job is a function named darwinChecker which takes the departure station, arrival station and the time I'm interested in. Like so `darwinChecker(train_station['home_station'], train_station['connect_station'], user_time['morning_time'])`. This just prints the details I'm after. Let me know if you need more information and I'll do my best to provide it! – Pixxel Dec 13 '18 at 22:43
  • Did you try to use code example code as given in https://github.com/dbader/schedule ? Does the package load ok? Try printing print schedule.__file__ – Adam Dec 13 '18 at 22:54
  • I've tried to run the example code, and nothing appears to get printed. If I add `print(schedule.__file__)` I just get a print of the python directory C:\Python\lib\site-packages\schedule\__init__.py, which is not where my original program is. – Pixxel Dec 13 '18 at 23:03
  • I realised that I didn't have the `while True: schedule.run_pending() time.sleep(1)`, so that now runs the code example. But now with the function outlined in my original post, I get `TypeError: the first argument must be callable` – Pixxel Dec 13 '18 at 23:11
  • That's why you should be posting full code next time. I believe second part of this you can solve with: https://stackoverflow.com/questions/26583557/typeerror-the-first-argument-must-be-callable – Adam Dec 13 '18 at 23:14
  • Thank you very much, the schedule module now works after having comma separated the function name and parameters! I had noticed this before, but did not have the while loop in yet! However, my original plan of running every Friday from 07:30 till 08:40, every 5 minutes still throws a AttributeError like in the OP. Here's the code I'm trying to use: `schedule.every().day.at("07:30").every(5).minutes.do(darwinChecker,train_station['home_station'], train_station['connect_station'], user_time['morning_time'])` – Pixxel Dec 13 '18 at 23:36
  • I assume you have function called darwinChecker but for some reason you have also defined something called Job that is not correct. Please edit OP and add full code for what you are trying to do as it's hard to guess. You can cut out any sensitive data if that's your concern. Ps- It would help me if you upvote helpful comments :) – Adam Dec 13 '18 at 23:46
  • Thanks Adam, I've added the full code in. It appears I'm limited by reputation from upvoting comments still. – Pixxel Dec 14 '18 at 09:30
  • Thanks. I will try myself once I get some time – Adam Dec 15 '18 at 13:08

0 Answers0