'Using module schedule run schedule immediately then again every hour

Im trying to schedule a task with the module "schedule" for every hour. My problem is i need the task to first run then run again every hour.

This code works fine but it waits an hour before initial run

import schedule
import time

def job():
    print("This happens every hour")

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

while True:
    schedule.run_pending()

I would like to avoid doing this:

import schedule
import time

def job():
    print("This happens immediately then every hour")

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

while i == 0: 
    job()
    i = i+1

while i == 1:
    schedule.run_pending()

Ideally it would be nice to have a option like this:

schedule.run_pending_now()


Solution 1:[1]

To run all jobs regardless if they are scheduled to run or not, use schedule.run_all(). Jobs are re-scheduled after finishing, just like they would if they were executed using run_pending().


def job_1():
    print('Foo')

def job_2():
    print('Bar')

schedule.every().monday.at("12:40").do(job_1)
schedule.every().tuesday.at("16:40").do(job_2)

schedule.run_all()

# Add the delay_seconds argument to run the jobs with a number
# of seconds delay in between.
schedule.run_all(delay_seconds=10)```

Solution 2:[2]

If you have many tasks that takes some time to execute and you want to run them independently during start you can use threading

import schedule
import time

def job():
    print("This happens every hour")

def run_threaded(task):
    job_thread = threading.Thread(target=task)
    job_thread.start()

run_threaded(job)       #runs job once during start

schedule.every().hour.do(run_threaded, job)
while True:
    schedule.run_pending()  # Runs every hour, starting one hour from now.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2229336
Solution 2 sam