
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Private Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Walrus Operator
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Floating Points
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Conditional User Inputs
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Packing and Unpacking
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Namedtuple
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Multiple Inheritance
- Python - Multilevel Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python - Data Classes
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Warnings
- Python - Built-in Exceptions
- Python - Debugger (PDB)
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Generator Expressions
- Python - Lambda Expressions
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - Odds and Ends
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python - Domain Specific Language (DSL)
- Python - Data Model
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - Thread Scheduling
Thread scheduling in Python is a process of deciding which thread runs at any given time. In a multi-threaded program, multiple threads are executed independently, allowing for parallel execution of tasks. However, Python does not have built-in support for controlling thread priorities or scheduling policies directly. Instead, it relies on the operating system's thread scheduler.
Python threads are mapped to native threads of the host operating system, such as POSIX threads (pthreads) on Unix-like systems or Windows threads. The operating system's scheduler manages the execution of these threads, including context switching, thread priorities, and scheduling policies. Python provides basic thread scheduling capabilities through thethreading.Timer class and thesched module.
In this tutorial will learn the basics of thread scheduling in Python, including how to use thesched module for scheduling tasks and thethreading.Timer class for delayed execution of functions.
Scheduling Threads using the Timer Class
TheTimer class of the Pythonthreading module allows you to schedule a function to be called after a certain amount of time. This class is a subclass ofThread and serves as an example of creating custom threads.
You start a timer by calling itsstart() method, similar to threads. If needed, you can stop the timer before it begins by using thecancel() method. Note that the actual delay before the action is executed might not match the exact interval specified.
Example
This example demonstrates how to use thethreading.Timer() class to schedule and manage the execution of tasks (custom threads) in Python.
import threadingimport time# Define the event functiondef schedule_event(name, start): now = time.time() elapsed = int(now - start) print('Elapsed:', elapsed, 'Name:', name)# Start timestart = time.time()print('START:', time.ctime(start))# Schedule events using Timert1 = threading.Timer(3, schedule_event, args=('EVENT_1', start))t2 = threading.Timer(2, schedule_event, args=('EVENT_2', start))# Start the timerst1.start()t2.start()t1.join()t2.join()# End timeend = time.time()print('End:', time.ctime(end))On executing the above program, it will produce the following output −
START: Tue Jul 2 14:46:33 2024Elapsed: 2 Name: EVENT_2Elapsed: 3 Name: EVENT_1End: Tue Jul 2 14:46:36 2024
Scheduling Threads using thesched Module
Thesched module in Python's standard library provides a way to schedule tasks. It implements a generic event scheduler for running tasks at specific times. It provides similar tools like task scheduler in windows or Linux.
Key Classes and Methods of the sched Module
Thescheduler() class is defined in thesched module is used to create a scheduler object. Here is the syntax of the class −
scheduler(timefunc=time.monotonic, delayfunc=time.sleep)
The methods defined in scheduler class include −
scheduler.enter(delay, priority, action, argument=(), kwargs={}) − Events can be scheduled to run after a delay, or at a specific time. To schedule them with a delay, enter() method is used.
scheduler.cancel(event) − Remove the event from the queue. If the event is not an event currently in the queue, this method will raise a ValueError.
scheduler.run(blocking=True) − Run all scheduled events.
Events can be scheduled to run after a delay, or at a specific time. To schedule them with a delay, use the enter() method, which takes four arguments.
A number representing the delay
A priority value
The function to call
A tuple of arguments for the function
Example
This example demonstrates how to schedule events to run after a delay using thesched module. It schedules two different events −
import schedimport timescheduler = sched.scheduler(time.time, time.sleep)def schedule_event(name, start): now = time.time() elapsed = int(now - start) print('elapsed=',elapsed, 'name=', name)start = time.time()print('START:', time.ctime(start))scheduler.enter(2, 1, schedule_event, ('EVENT_1', start))scheduler.enter(5, 1, schedule_event, ('EVENT_2', start))scheduler.run()# End timeend = time.time()print('End:', time.ctime(end))It will produce the followingoutput −
START: Tue Jul 2 15:11:48 2024elapsed= 2 name= EVENT_1elapsed= 5 name= EVENT_2End: Tue Jul 2 15:11:53 2024
Example
Let's take another example to understand the concept better. This example schedules a function to perform an addition after a 4-second delay using thesched module in Python.
import schedfrom datetime import datetimeimport timedef addition(a,b): print("Performing Addition : ", datetime.now()) print("Time : ", time.monotonic()) print("Result {}+{} =".format(a, b), a+b)s = sched.scheduler()print("Start Time : ", datetime.now())event1 = s.enter(4, 1, addition, argument = (5,6))print("Event Created : ", event1)s.run()print("End Time : ", datetime.now())It will produce the followingoutput −
Start Time : 2024-07-02 15:18:27.862524Event Created : Event(time=2927111.05638099, priority=1, sequence=0, action=<function addition at 0x7f31f902bd90>, argument=(5, 6), kwargs={})Performing Addition : 2024-07-02 15:18:31.866381Time : 2927111.060294749Result 5+6 = 11End Time : 2024-07-02 15:18:31.866545