Python 简明教程

Python - Thread Scheduling

Python 中的线程调度是一个在任何给定时间决定运行哪个线程的过程。在多线程程序中,多个线程独立执行,允许并行执行任务。然而,Python 没有内置支持来直接控制线程优先级或调度策略。相反,它依赖于操作系统的线程调度程序。

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 线程映射到主机操作系统的本机线程,例如类 Unix 系统上的 POSIX 线程 (pthread) 或 Windows 线程。操作系统的调度程序管理这些线程的执行,包括上下文切换、线程优先级和调度策略。Python 通过 threading.Timer 类和 sched 模块提供基本的线程调度功能。

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 the threading.Timer class and the sched module.

在本教程中,您将学习 Python 中线程调度的基础知识,包括如何使用 sched 模块安排任务以及 threading.Timer 类延迟执行函数。

In this tutorial will learn the basics of thread scheduling in Python, including how to use the sched module for scheduling tasks and the threading.Timer class for delayed execution of functions.

Scheduling Threads using the Timer Class

Python threading 模块的 Timer 类允许您安排一个函数在一段时间后调用。该类是 Thread 的子类,用作创建自定义线程的示例。

The Timer class of the Python threading module allows you to schedule a function to be called after a certain amount of time. This class is a subclass of Thread and serves as an example of creating custom threads.

您可以通过调用 start() 方法启动一个计时器,类似于线程。如果需要,您可以在它通过使用 cancel() 方法开始前停止计时器。请注意,在执行操作之前的实际延迟可能与指定的精确时间间隔不符。

You start a timer by calling its start() method, similar to threads. If needed, you can stop the timer before it begins by using the cancel() method. Note that the actual delay before the action is executed might not match the exact interval specified.

Example

此示例演示如何使用 threading.Timer() 类安排和管理 Python 中任务(自定义线程)的执行。

This example demonstrates how to use the threading.Timer() class to schedule and manage the execution of tasks (custom threads) in Python.

import threading
import time

# Define the event function
def schedule_event(name, start):
   now = time.time()
   elapsed = int(now - start)
   print('Elapsed:', elapsed, 'Name:', name)

# Start time
start = time.time()
print('START:', time.ctime(start))

# Schedule events using Timer
t1 = threading.Timer(3, schedule_event, args=('EVENT_1', start))
t2 = threading.Timer(2, schedule_event, args=('EVENT_2', start))

# Start the timers
t1.start()
t2.start()

t1.join()
t2.join()
# End time
end = 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 2024
Elapsed: 2 Name: EVENT_2
Elapsed: 3 Name: EVENT_1
End: Tue Jul  2 14:46:36 2024

Scheduling Threads using the sched Module

Python 标准库中的 sched 模块提供了一种安排任务的方法。它为在特定时间运行任务实现了一个通用事件调度程序。它提供了类似于 Windows 或 Linux 中的任务计划程序的工具。

The sched 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

scheduler() 类在 sched 模块中定义,用于创建调度程序对象。以下是该类的语法:

The scheduler() class is defined in the sched 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 −

  1. 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.

  2. 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.

  3. scheduler.run(blocking=True) − Run all scheduled events.

可以安排在延迟或特定时间后运行事件。要安排延迟,请使用 enter() 方法,它需要四个参数。

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.

  1. A number representing the delay

  2. A priority value

  3. The function to call

  4. A tuple of arguments for the function

Example

此示例演示如何使用 sched 模块在延迟后安排事件运行。它安排两个不同的事件:

This example demonstrates how to schedule events to run after a delay using the sched module. It schedules two different events −

import sched
import time

scheduler = 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 time
end = time.time()
print('End:', time.ctime(end))

它将生成以下 output

It will produce the following output

START: Tue Jul  2 15:11:48 2024
elapsed= 2 name= EVENT_1
elapsed= 5 name= EVENT_2
End: Tue Jul  2 15:11:53 2024

Example

让我们再举一个示例来更好地理解这个概念。此示例使用 Python 中的 sched 模块在延迟 4 秒后安排一个函数执行加法。

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 the sched module in Python.

import sched
from datetime import datetime
import time

def 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())

它将生成以下 output

It will produce the following output

Start Time :  2024-07-02 15:18:27.862524
Event 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.866381
Time :  2927111.060294749
Result 5+6 = 11
End Time :  2024-07-02 15:18:31.866545