Python  

Task Schedule Library in Python

In Python, several libraries are available to schedule a program and achieve a task. Here, we do not need to run programs or Python scripts manually; instead, we automate the code. Schedule is a library or package supported in python which allows us to schedule a particular function or program. It will be useful in cases like running a task only once or at a particular time every day, weekly, or monthly.

Here is a simple example for scheduling a task. To use the Schedule library, first, we need to install it.

pip install schedule

Then run the code below.

schedule_Example.py

import schedule
import time

def PrintMsg():
    print("SCHEDULED for every 10 Secs...||", time.strftime("%H:%M:%S"))

schedule.every(10).seconds.do(PrintMsg)

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

Output

Output

In this example, time. The strftime method is used to print a time every 10 seconds. Also, iterate for each one second using a while loop and time. sleep(1).

Consider how our smartphones provide daily and hourly weather updates. A scheduling method like this might be used to deliver regular notifications and updates.

For example, in the below Python code, an hourly, daily, and weekly schedule is implemented.

import schedule
import time

def PrintMsg(Msg):
    print("SCHEDULED for", Msg, time.strftime("%H:%M:%S"))

# Every hour
schedule.every().hour.do(lambda: PrintMsg("HOUR"))

# Every day at 12:10 PM
schedule.every().day.at("12:10").do(lambda: PrintMsg("AT 12:10"))

# Every 5 to 10 minutes
schedule.every(5).to(10).minutes.do(lambda: PrintMsg("Every 5 to 10 minutes"))

# Every day at 12:47 PM Amsterdam time
schedule.every().day.at("12:47", "Europe/Amsterdam").do(lambda: PrintMsg("Europe"))

# Every minute at 45 seconds
schedule.every().minute.at(":45").do(lambda: PrintMsg("Every 45th second"))

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

Output

Output

In this example, the PrintMsg method is called by the schedule class using a lambda expression to pass the variable to differentiate the hour and minute schedule. With this, I conclude how we can automate the task using the schedule library.