Table of Contents
? Basic usage examples
? Cancel the timed task (important!)
? Repeat the timing task (cycle timer)
? Common precautions
Home Backend Development Python Tutorial python threading timer example

python threading timer example

Jul 29, 2025 am 03:05 AM
python

threading.Timer executes functions asynchronously after a specified delay without blocking the main thread, and is suitable for handling lightweight delays or periodic tasks. ① Basic usage: Create a Timer object and call the start() method to delay the execution of the specified function; ② Cancel the task: Calling the cancel() method before the task is executed can prevent execution; ③ Repeating execution: Enable periodic operation by encapsulating the RepeatingTimer class; ④ Notes: Each Timer starts a new thread, and resources should be managed reasonably. Call cancel() if necessary to avoid memory waste. When the main program exits, you need to pay attention to the influence of non-daemon threads. It is suitable for delayed operations, timeout processing, and simple polling. It is simple but very practical.

python threading timer example

Python's threading.Timer is a very practical tool that allows you to execute a function after specifying a delay, and this execution is asynchronous (does not block the main thread). Below is a simple and easy-to-understand threading.Timer example, suitable for beginners to understand and use.

python threading timer example

? Basic usage examples

 import threading

def my_task():
    print("The timing task has been executed!")

# Create a timer: execute my_task function timer = threading.Timer(5.0, my_task)

# Start timer timer.start()

print("The main thread continues to run...")

Output effect:

 The main thread continues to run...
(Wait 5 seconds later)
The scheduled task is executed!

✅ Note: Timer runs in child threads, so it does not block the main thread.

python threading timer example

? Cancel the timed task (important!)

Sometimes you may want to cancel the task before it is executed, such as the user operation changes the state.

 import threading
import time

def my_task():
    print("Task was executed!")

timer = threading.Timer(5.0, my_task)
timer.start()

print("Timer started")

# The simulation decides to cancel the task after 3 seconds time.sleep(3)

if timer.is_alive():
    timer.cancel()
    print("Timer cancelled")

Output:

python threading timer example
 Timer is started (after 3 seconds)
Timer cancelled

❗ If cancel() is called before run() , the task will not be executed.


? Repeat the timing task (cycle timer)

Timer is executed only once by default. If you want it to run periodically, you can encapsulate it yourself:

 import threading

class RepeatingTimer:
    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.timer = None
        self.is_running = False

    def _run(self):
        self.is_running = False
        self.start() # Restart the timer self.function(*self.args, **self.kwargs) # Execute the task def start(self):
        if not self.is_running:
            self.timer = threading.Timer(self.interval, self._run)
            self.timer.start()
            self.is_running = True

    def stop(self):
        if self.timer is not None:
            self.timer.cancel()
        self.is_running = False

# Use example def says_hello():
    print("Hello, I execute it every 2 seconds")

rt = RepeatingTimer(2.0, say_hello)
rt.start()

# Stop import time after running for 10 seconds
time.sleep(10)
rt.stop()
print("Timer stopped")

? Common precautions

  • Timer inherits from Thread , so each timer will open a new thread.
  • If you create a large number of Timer objects, it may consume more resources.
  • Don't forget to call cancel() to avoid unnecessary execution.
  • When the main program exits, Timer of the non-daemon thread will prevent the program from exiting. You can set timer.daemon = True (but it is generally not recommended to set it at will).

Basically that's it. threading.Timer is suitable for lightweight, delayed or periodic tasks, such as:

  • Delayed sending of messages
  • Timeout processing (such as connection timeout)
  • Simple polling or heartbeat mechanism

Not complicated, but very practical.

The above is the detailed content of python threading timer example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
python seaborn jointplot example python seaborn jointplot example Jul 26, 2025 am 08:11 AM

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

python list to string conversion example python list to string conversion example Jul 26, 2025 am 08:00 AM

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python pandas melt example python pandas melt example Jul 27, 2025 am 02:48 AM

pandas.melt() is used to convert wide format data into long format. The answer is to define new column names by specifying id_vars retain the identification column, value_vars select the column to be melted, var_name and value_name, 1.id_vars='Name' means that the Name column remains unchanged, 2.value_vars=['Math','English','Science'] specifies the column to be melted, 3.var_name='Subject' sets the new column name of the original column name, 4.value_name='Score' sets the new column name of the original value, and finally generates three columns including Name, Subject and Score.

python django forms example python django forms example Jul 27, 2025 am 02:50 AM

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.

Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? Jul 30, 2025 pm 09:12 PM

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

python iter and next example python iter and next example Jul 29, 2025 am 02:20 AM

iter() is used to obtain the iterator object, and next() is used to obtain the next element; 1. Use iterator() to convert iterable objects such as lists into iterators; 2. Call next() to obtain elements one by one, and trigger StopIteration exception when the elements are exhausted; 3. Use next(iterator, default) to avoid exceptions; 4. Custom iterators need to implement the __iter__() and __next__() methods to control iteration logic; using default values is a common way to safe traversal, and the entire mechanism is concise and practical.

See all articles