简体   繁体   中英

schedule a python script to run every hour

I am trying to write a script that executes every hour but, when I run it... it takes an hour to run the job for the first time and then, it starts running like every 5 seconds I don't understand what am I doing wrong here

from apscheduler.schedulers.blocking import BlockingScheduler

def job():
    print('excuting job')


scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', hours = 1)
scheduler.start()

this is another code that I have used, but it's the same result

schedule.every().hour.do(job)

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

Don't do it in python. Make a file called exehour.bat with this (assuming you're using Windows):

@echo off
cd DIRECTORY-OF-FILE
:loop
timeout 3600
FILE-NAME
goto loop

So this will execute a file every 1 hour when you run it Or if you need it in python

import time
def runhour():
   #YOUR PYTHON CODE GOES UNDERNEATH HERE


   #
   time.sleep(3600)
    

Might have something to do within your def, like a rogue brake or other bad while loop or sleep timer. Maybe the checking job timer not being short enough is affecting something as well?

import schedule # I'm not sure about the BlockingScheduler import but this one works for me
import time     # Hate how we need an import for this and it's not built into python....

def job():
    print('executing job')

# Run your job on first boot without the scheduler
job()

# Then setup the schedule to be used from now on
schedule.every().hour.do(job)

# Check every second if we can do our job yet or not
# Bonus heartbeat . so you know the while loop is running and not crashed.
while True:
    schedule.run_pending()
    print(".", end="", flush=True)
    time.sleep(1) # seconds

If it runs our job() then gets stuck, boot loops or crashes then its in your job def. if it runs fine the first time, sets up the schedule fine but then gets stuck with executing the schedule then I don't really have any ideas without seeing more of the job() def.. for shits and giggles you could pip uninstall and reinstall schedule again and see if that helps idk..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM