Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Autorun a Python script on windows startup
Next article icon

How to Schedule a Task in Python?

Last Updated : 15 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We will see what is task scheduling in Python and how to schedule a task in Python with examples. In this article, we will see how we can schedule a task in Python.

What is Task Scheduling in Python?

Task scheduling involves automating processes by defining tasks to be executed at predetermined times or intervals. In Python, task scheduling simplifies repetitive operations by allowing developers to schedule tasks to run autonomously, enhancing productivity and efficiency.

Key Concepts:

  • Task Scheduling: Task scheduling entails automating processes by defining tasks to be executed at predetermined times or intervals.
  • schedule Library: Python's schedule library simplifies task scheduling with a straightforward and intuitive syntax.
  • Time-Based Scheduling: Tasks can be scheduled to run at precise times using the at() method.
  • Interval-Based Scheduling: The every() method enables tasks to be scheduled at regular intervals.
  • Task Functions: Task functions are Python functions executed when scheduled tasks are triggered.

How to Schedule a Task in Python?

Below, are the examples of how to schedule a task In Python With Examples.

  • Schedule Task at Specific Time
  • Schedule Task at Specific Intervals
  • Python Automated Email Scheduler

To schedule tasks in Python using the schedule library, First install the schedule library, use the following command:

pip install schedule

After installing the library, import the necessary modules (schedule and time) in your Python script using the following commands:

import schedule import time 

Schedule Task at Specific Time

In this example, in below Python code the `schedule` library to schedule a daily task of printing a specific message at 10:35 AM. The code enters an infinite loop, checking for pending tasks and executing them while avoiding high CPU usage by incorporating a 1-second sleep interval.

Python3
import schedule import time  # Define a function to print a message   def print_message():     print("Hello! It's time to code on GFG")   # Schedule the task to run every day at 7:00 AM schedule.every().day.at("10:35").do(print_message)  while True:     schedule.run_pending()     time.sleep(1) 

Output

PRINT_AT_SPECIFIC_TIME

Schedule Task at Intervals

In this example, in below Python code, the `schedule` library is employed to execute a task every 5 seconds. The task, defined by the `print_message()` function, prints the current time. below code runs indefinitely, checking and executing pending tasks while incorporating a 1-second sleep interval for efficiency.

Python3
import schedule import time   def print_message():     print("Task executed at:", time.strftime("%H:%M:%S"))   # Schedule task to run every 5 seconds schedule.every(5).seconds.do(print_message)  # Keep the program running to allow scheduled tasks to execute while True:     schedule.run_pending()     time.sleep(1) 

Output

PRINT_AT_5_sec

Python Automated Email Scheduler

In this example, In this Python code, the `schedule` library is utilized to schedule a task. The function `send_email()` is defined to simulate sending an email, and the task is scheduled to run every day at 11:53 PM using `schedule.every().day.at("23:53").do(send_email)`. below code runs continuously, checking and executing pending tasks while ensuring efficiency with a 1-second sleep interval.

Python3
import schedule import time  # Define a function to send email def send_email():     print("Email sent at:", time.strftime("%H:%M:%S"))  # Schedule the task to run every day at 11:53 pm schedule.every().day.at("23:53").do(send_email)  # Keep the program running to allow scheduled tasks to execute while True:     schedule.run_pending()     time.sleep(1) 

Output

email_schedule
email_scheduling

Next Article
Autorun a Python script on windows startup

T

theoprix
Improve
Article Tags :
  • Python
  • Python Programs
  • Python-datetime
Practice Tags :
  • python

Similar Reads

  • How to clear screen in python?
    When working in the Python interactive shell or terminal (not a console), the screen can quickly become cluttered with output. To keep things organized, you might want to clear the screen. In an interactive shell/terminal, we can simply use ctrl+l But, if we want to clear the screen while running a
    5 min read
  • Schedule a Python Script on PythonAnywhere
    Keeping the computer on 24/7 is not practical, so if you want to execute a Python script at a particular time every day, you probably need a computer that is ON all the time. To make this possible, a website PythonAnywhere gives you access to such a 24/7 computer. You can upload a Python script and
    2 min read
  • How To Install Pytz In Python?
    In this article, we will explain how to install Pytz in Python, explore its features, and provide visual guidance with images. After installation, we will execute a code snippet to show its successful functionality. What is Pytz In Python?Pytz is a Python library that provides support for working wi
    3 min read
  • How to make a Twitter Bot in Python?
    Twitter is an American microblogging and social networking service on which users post and interact with messages known as "tweets". In this article we will make a Twitter Bot using Python. Python as well as Javascript can be used to develop an automatic Twitter bot that can do many tasks by its own
    3 min read
  • Autorun a Python script on windows startup
    Adding a Python script to windows start-up basically means the python script will run as the windows boots up. This can be done by two step process - Step #1: Adding script to windows Startup folder After the windows boots up it runs (equivalent to double-clicking) all the application present in its
    2 min read
  • How to Run Two Async Functions Forever - Python
    In Python, asynchronous programming allows us to run multiple tasks concurrently without blocking the main program. The most common way to handle async tasks in Python is through the asyncio library. Key Concepts Coroutines: Functions that we define using the async keyword. These functions allow us
    4 min read
  • How to make a Python program wait?
    The goal is to make a Python program pause or wait for a specified amount of time during its execution. For example, you might want to print a message, but only after a 3-second delay. This delay could be useful in scenarios where you need to allow time for other processes or events to occur before
    2 min read
  • How to Parallelize a While loop in Python?
    Parallelizing a while loop in Python involves distributing the iterations of a loop across multiple processing units such as the CPU cores or computing nodes to execute them concurrently. This can significantly reduce the overall execution time of the loop, especially for tasks that are CPU-bound or
    2 min read
  • Python Script to Shutdown Computer
    As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to shutdown a computer. To shut down the computer/PC/laptop by using a Python script, you have to use the os.system() function with the code "shutdown /s /t 1" . Note:
    1 min read
  • Flight-price checker using Python and Selenium
    Python is a scripting language with many extended libraries and frameworks. It is used in various fields of computer science such as web development and data science. Also, Python can be used to automate some minor tasks which can be really helpful in the long run. The Python script mentioned in thi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences