-1

I want a python file to run automatically at 8am every day going forward. I try to use the library schedule as pointed out in the second answer here, in Windows.

import schedule
import time

def query_fun(t):

  print('Do a bunch of things')
  print("I'm working...", t)
  df.to_csv('C:/Documents/Query_output.csv', encoding='utf-8')

schedule.every().day.at("08:00").do(query_fun, 'It is 08:00')


while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

But 8am has come and gone, and the csv file hasn't been updated, and it doesn't look like the script runs when I want it to.

Edit: Based on this, I used pythonw.exe to run the script in the command line: C:\Program Files\Python3.7>pythonw.exe daily_query.py but the script doesn't run when expected.

Jojo
  • 1,117
  • 2
  • 15
  • 28

2 Answers2

1

You took out the key part of the script by commenting it out. How is the script magically supposed to rise up at 8 AM to do something? The point is to always keep it running and trigger at the right time using the mechanism provided by schedule library (running any pending jobs at time T on day D that is). What you are doing right now is just declaring the method and exiting without doing anything.

The point is to keep the script running in background and trigger the function by matching the current time with the time specified, running any pending assigned jobs as per your logic. You run your script in background and forget about it until 8 AM:

nohup python MyScheduledProgram.py &

nohup will take care that your terminal doesn’t get any output printed on it from the program. You can view the output from nohup.out though.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
0

Here you can easily see what the skript does:

schedule.every().day.at("08:00").do(query_fun, 'It is 08:00')

tells the scheduler to run the function if it is 8am. But the other part of the library is this one:

while True:
schedule.run_pending()
time.sleep(60) # wait one minute

this part checks if it should start a skript, then it waits for 60 seconds, and checks again.

EDIT:

The question was related to a Windows machine, therefore my answer has no point here.

If you are on a linux machine, you should consider using crontabs:

Open a terminal and type crontab -e

After you selected the editor you wanted (lets take nano) it opens a list, where you can add various entries

just add:

0 8 * * * /usr/bin/python3 /home/path/to/skript.py

Then save with STRG + O and exit nano with STRG + X

The skript will run everyday at 8am, just test the command

/usr/bin/python3 /home/path/to/skript.py 

to make sure the skript does not produce an error

  • Does the line `df.to_csv('C:/Documents/Query_output.csv'...)` tell you anything about whether the asker is using Linux, and hence whether they can use `cron`? – Luke Woodward Dec 28 '20 at 19:42