Home Backend Development Python Tutorial Introduction to the method of implementing loop timer in Python (with code)

Introduction to the method of implementing loop timer in Python (with code)

Mar 14, 2019 am 11:13 AM
python

This article brings you an introduction to the method of implementing a loop timer in python (with code). It has a certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.

Python How to write a timer to perform a certain operation in a loop?

Timer object

from threading import Timer
def hello(): 
    print "hello, world" 
   
t = Timer(10.0, hello) 
t.start()
Copy after login

Output after 10 seconds:

hello, world
Copy after login

Focus on the code t = Timer(10.0, hello), python provides a Timer object, it will Perform an operation after the specified time; its full form:

class threading.Timer(interval, function, args=[], kwargs={})
Copy after login

interval is the time interval, function is a callable object, and args and kwargs will be used as parameters of function.

Note: The function will only be executed once and will not be executed regularly, and Timer will create a new thread when executing the operation.

There is a slight difference between Timer in python2 and python3:

# python2.7
def Timer(*args, **kwargs):
    return _Timer(*args, **kwargs)
# python3.7
class Timer(Thread):
    pass
Copy after login

In python3, Timer is a subclass of Thread; in python2, _Timer is a subclass of Thread, and Timer is just a factory method of the _Timer class.

The above code will only print hello, world once and then exit. So how to print at intervals in a loop?

Rough loop timer

One way is to continue to register a Timer in the function, so that the function can continue to be executed at the next interval;

from threading import Timer
def hello(): 
    print "hello, world" 
    Timer(10.0, hello) .start()

t = Timer(10.0, hello) 
t.start()
Copy after login

Every 10 seconds Output a hello, world.

The effect is achieved, but there seems to be some problem here. Back to the Timer itself, it is a thread. Every time the cycle interval is operated, the system has to create a thread and then recycle it, which is very expensive for the system. If the time interval interval is very short, the system will create many threads at once, and these threads are difficult to recycle quickly, causing system memory and CPU resources to be consumed.
So it is not recommended to continue to register a Timer in the function.

More pythonic loop timer

Here is a more pythonic method:

from threading import _Timer
def hello():
     print "hello, world"
class RepeatingTimer(_Timer): 
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)
t = RepeatingTimer(10.0, hello)
t.start()
Copy after login

Focus on the RepeatingTimer class, which inherits threading._Timer, but rewrites the parent class run method. This is how Python2 is written. RepeatingTimer in python3 should inherit threading.Timer.

Why should we override the run method of Thread?

_Timer is a Thread subclass. Let’s first look at the run usage of the Thread class.

from threading import Thread
def hello():
     print "hello, world"
# 继承 Thread
class MyThread(Thread):
    # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
    def run(self):
        hello()
t = MyThread()
t.start()
Copy after login

Complete definition of Thread object:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
Copy after login

The run method code:

class Thread(_Verbose):
    def run(self):
        try:
            if self.__target:
                self.__target(*self.__args, **self.__kwargs)
        finally:
            # Avoid a refcycle if the thread is running a function with
            # an argument that has a member that points to the thread.
            del self.__target, self.__args, self.__kwargs
Copy after login

The standard run method is used to execute the target method passed in by the user to the constructor. Subclasses can override the run method and write the code to be executed into run. After the thread is created, the run() method will be run when the user calls the start() method.

So RepeatingTimer overrides the run() method of _Timer, which can change the execution body of the thread. When we call the start() method of RepeatingTimer, the run() method we rewrite will be executed.

Look at the while not self.finished.is_set() statement in the RepeatingTimer class. self.finished.is_set() will not exit the loop until True and the timer will end. finished is a threading.Event object. An Event object manages a flag, which can be set to True by the set() method or set to False by the clear() method. When calling wait([timeout]), the thread will sleep until the flag is True or the timeout expires. .

We know that the timer has a cancel() method that can cancel the operation in advance. It actually calls the Event.clear() method to let the wait method end waiting in advance, and determines that the timer operation will not be performed when the flag is true. Specific code:

class _Timer(Thread):
    """Call a function after a specified number of seconds:
            t = Timer(30.0, f, args=[], kwargs={})
            t.start()
            t.cancel() # stop the timer's action if it's still waiting
    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()
Copy after login

So the run method of RepeatingTimer will always execute the while loop body. In the loop body, the function object passed in by the user will be executed and wait for the specified time. When the user wants to exit the timer, he only needs to call the cancel method and set the flag to True so that the loop body will not continue to execute. This completes a pretty good loop timer.

The above is the detailed content of Introduction to the method of implementing loop timer in Python (with code). 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles