DEV Community

Cover image for A Simple Scheduler in Python
Bhupesh Varshney ๐Ÿ‘พ
Bhupesh Varshney ๐Ÿ‘พ

Posted on • Edited on • Originally published at bhupesh-v.github.io

A Simple Scheduler in Python

We all encounter things in life which we want to automate, Setting up reminders and schedules are one of them

Python makes it easy for all the developers out there to make small python scripts that can schedule some boring stuff for you.

Here comes this #awesome library called schedule

(quite a name it got there ๐Ÿ˜‰)

Let's start around by playing with this

Installation

First things first let us install the python package first



pip install schedule  


Enter fullscreen mode Exit fullscreen mode

Introduction

schedule is an in-process scheduler for periodic jobs that uses the builder pattern for configuration. Schedule lets you run Python functions (or any other callable) periodically at predetermined intervals using a simple, human-friendly syntax.

Python job scheduling for humans.

Let's not worry about what in-process scheduling is for now

Let's write some code



import schedule  

def job():  
    print("A Simple Python Scheduler.")  

# run the function job() every 2 seconds  
schedule.every(2).seconds.do(job)  

while True:  
    schedule.run_pending()  


Enter fullscreen mode Exit fullscreen mode

The above code prints A Simple Python Scheduler. every 2 seconds.

scheduler

Let's understand line by line

  • import schedule
    This needs no explaining just importing the package to use.

  • def job()
    This is the function which we want to execute according to our schedule.

  • schedule.every(2).seconds.do(job)
    This is where magic happens

    A job is created and returned by Scheduler.every() method, which also defines its interval (in time units) here the interval is in seconds*.

    The do() specifies the job_func that should be called every time the job runs.

    Any additional arguments are passed on to job_func when the job runs.

    i.e the statement
    schedule.every(2).seconds.do(job(argument)) would give an error
    instead use

    schedule.every(2).seconds.do(job, arg1, arg2)

  • schedule.run_pending()
    The run_pending() just runs all jobs that are scheduled to run.
    Make sure to run it in a loop because so that the scheduling task keeps on running all time.

Hurray we wrote our very first Scheduler using Python
hurray

Other Variations



import schedule
import time

def job():
    print("I'm working...")

def job2():
    print("yo boiss..")

def job3():
    print("Hello")

schedule.every(5).seconds.do(job)
# some other variations 
schedule.every().hour.do(job)
schedule.every().day.at("12:25").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().thursday.at("19:15").do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)
schedule.every(2).seconds.do(job2)

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


Enter fullscreen mode Exit fullscreen mode

Above are some other ways through which we can schedule jobs

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

    This executes the job() function every hour

  • schedule.every().day.at("12:25").do(job)

    This executes the job() function every day at 12:25 PM
    By default schedule uses 24 hr format.

  • schedule.every().wednesday.at("13:15").do(job)

    Do job() every Wednesday at 1:15 PM.
    You can also specify day-names to run a particular job.
    See the list of available ones.

  • schedule.every(2).to(5).minutes.do(job3)

    This one executes job3() every 2 to 5 minutes ;)

Bonus Stuff

yeahh

So now you are able to schedule things
What if you could remind yourself of some items to do ??

๏ฟผsmtplib comes to the rescue.

Using smtplib you can send emails (emails will come in the spam folder though ๐Ÿ™ƒ)

Here is a simple script to send emails using python



import smtplib


def sendEmail(sender_email, password, to, subject, msg):
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender_email, password)

        message = f'From: {sender_email}\nTo: {to}\nSubject: {subject}\n\n{msg}'
        print(message)

        server.sendmail(sender_email, to, message)
        server.quit()
        print("Email Sent")
    except:
        print("Some Error Occured")

if __name__ == '__main__':
    SENDER_EMAIL = "youremail@xyz.com"
    PASSWORD = "password"
    TO = "yourfrnds@email.com"
    SUBJECT = "Just having fun"
    MESSAGE = "hey dawg! it's my first Email"
    sendEmail(SENDER_EMAIL, PASSWORD, TO, SUBJECT, MESSAGE)



Enter fullscreen mode Exit fullscreen mode

Now go check your spam folder ๐Ÿ˜œ

I hope you liked this post ๐Ÿ˜„

Seems interesting?, Subscribe ๐Ÿš€ to read more such cool stuff or just connect with me on Twitter.

Top comments (6)

Collapse
 
jairajsahgal profile image
jairajsahgal

Mea toh tujhe insaan samajta tha, tu toh bhagwan nikla re
Deva re Deva
( I used to think you were human, but you found out to be god himself, oh lord oh lord )
Now I can schedule my selenium program for classes and can sleep peacefully.
I was unable to do because of crontab.
Thank you

Collapse
 
bhupesh profile image
Bhupesh Varshney ๐Ÿ‘พ

Glad I was able to help. thanks for reading

Collapse
 
anuragrana profile image
Anurag Rana

Great article.

We can trick Gmail to not send the emails in the spam folder by including few keywords like [urgent, important, password reset, otp, bank balance, resume, appointment, interview call etc] of size 0px if the content of the email is HTML.

Collapse
 
jadedanial profile image
Jade Danial

Great! I can use this in my personal project.

Does it not consume a lots of RAM?

Collapse
 
maniflames profile image
Maniflames

Hey that's pretty nice. Can you also run it in the background and get notified in the main when the job is done?

Collapse
 
bhupesh profile image
Bhupesh Varshney ๐Ÿ‘พ

Yeah sure one can run the scheduler in background by running it in a separate thread