Search code examples
pythonpython-3.xpython-2.7readfileschedule

Reading a file every 30 minutes in Python


As you see in the below code, it is possible to open a file in a directory and read it. now i want live_token read the file every 30 minutes and print it. Can anyone help me in this regard? I found below code as scheduling to do a job but i don't know how to do needful modifications.

schedule.every(30).minutes.do()

Sorry if this question is so basic, I am so new with Python.

def read_key():
    live_key_file_loc = r'C:\key.txt'
    live_key_file = open(live_key_file_loc , 'r')
    global key_token
    time.sleep(6)
    live_token=live_key_file.read()
    print(live_token)

Solution

  • @jonrsharpe is right. Refer to schedule usage. You should have a script which should keep running always to fetch the token every 30 minutes from the file. I have put below a script which should work for you. If you dont want to run this file in python always, look for implementing a scheduled job.

    import schedule
    import time
    
    def read_key():
        with open('C:\\key.txt' , 'r') as live_key_file_loc
            live_token = live_key_file_loc.read()
        print(live_token)
    
    schedule.every(30).minutes.do(read_key)
    
    while True:
        schedule.run_pending()
        time.sleep(1)