Easy Way to Scheduling Using Python

Feri Lukmansyah
Jun 1 · 2 min read
image from pexels.com

hello and welcome to other notes, The topic of discussion this time is how to do a scheduling function in python using the schedule module

that an interesting topic now let’s get started

now install schedule from pip

pip install schedule

look from PyPI

now let’s create a simple function to demonstrate how to scheduling in python

import time
import schedule

def jobs():
start: float = time.time()
print('Im Working hard')
end: float = time.time()
print(f"Time Estimated {end - start}")


# scheduling steps
schedule.every(5).seconds.do(jobs)

if __name__ == '__main__':
while True:
schedule.run_pending()
time.sleep(1)

In this function we calculate how many seconds it will take to run the function then we define the scheduler to run every 5 seconds, let’s look at this line

# scheduling steps
schedule.every(5).seconds.do(jobs)

or many examples like this

# Run job every 3 second/minute/hour/day/week,
# Starting 3 second/minute/hour/day/week from now
schedule.every(3).seconds.do(job)
schedule.every(3).minutes.do(job)
schedule.every(3).hours.do(job)
schedule.every(3).days.do(job)
schedule.every(3).weeks.do(job)

# Run job every minute at the 23rd second
schedule.every().minute.at(":23").do(job)

# Run job every hour at the 42rd minute
schedule.every().hour.at(":42").do(job)

# Run jobs every 5th hour, 20 minutes and 30 seconds in.
# If current time is 02:00, first execution is at 06:20:30
schedule.every(5).hours.at("20:30").do(job)

# Run job every day at specific HH:MM and next HH:MM:SS
schedule.every().day.at("10:30").do(job)
schedule.every().day.at("10:30:42").do(job)

# Run job on a specific day of the week
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)

Using Decorator to Scheduling Jobs

Using a @repeat to Pass it an interval using the same syntax as above while omitting the .do(). for example

import time
from schedule import run_pending, every, repeat


@repeat(every(10).minutes)
def job():
print("I am a scheduled job")


while True:
run_pending()
time.sleep(1)

Passing Arguments

do() passes extra arguments to the job function, for example

import schedule


def greet(name: str):
print('Hello', name)


schedule.every(2).seconds.do(greet, name='Alice')
schedule.every(4).seconds.do(greet, name='Bob')

from schedule import every, repeat


@repeat(every().second, "World")
@repeat(every().day, "Mars")
def hello(planet: str):
print("Hello", planet)

That’s a little note on how to easily schedule using Python, thank you, hope it’s useful, click here to join our community

References And Resource

Remote Worker Indonesia

Make Indonesia World #1 Remote Worker Provider