Hướng dẫn stop python

Tuy nhiên, khoảng thời gian được khởi tạo cho timer có thể sẽ không phải là tức thời, khi hành động thực sự được thực hiện bởi trình thông dịch, bởi vì việc thực sự lập lịch cho thread tương ứng của timer object là trách nhiệm của thread scheduler – trình lập lịch cho các luồng

Nội dung chính

  • 1. Tạo ra một đối tượng Timer
  • 2. Hủy đi một timer
  • Syntax for creating Timer object
  • Methods of Timer class
  • start() method
  • cancel() method
  • Time for an Example
  • Introduction to Python Threading Timer
  • Syntax of Python Threading Timer
  • Examples of Python Threading Timer
  • Recommended Articles

Timer là một sub-class (lớp con) của class Thread được định nghĩa trong Python. Nó được khởi động bằng cách gọi đến hàm start() tương ứng với timer.

1. Tạo ra một đối tượng Timer

Cú pháp:

threading.Timer(interval, function, args = None, kwargs = None)

Cú pháp trên sẽ tạo ra một timer, timer này sẽ khởi chạy hàm function với các đối số args và các đối số từ khóa (keyword arguments) kwargs, sau khi khoảng thời gian interval (đơn vị thời gian ở đây được dùng là giây) đã trôi qua. Nếu args là None (chính à giá trị mặc định của nó), thì một danh sách trống (empty list) sẽ được sử dụng. Nếu kwargs là None (chính là giá trị mặc định của nó), thì một từ điển trống (empty dict) sẽ được sử dụng.

Dưới đây là đoạn chương trình Python mô tả cách sử dụng timer objects trong Python:

# -----------------------------------------------------------
#Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
#@author cafedevn
#Contact: 
#Fanpage: https://www.facebook.com/cafedevn
#Group: https://www.facebook.com/groups/cafedev.vn/
#Instagram: https://instagram.com/cafedevn
#Twitter: https://twitter.com/CafedeVn
#Linkedin: https://www.linkedin.com/in/cafe-dev-407054199/
#Pinterest: https://www.pinterest.com/cafedevvn/
#YouTube: https://www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/
# -----------------------------------------------------------

# Program to demonstrate 
# timer objects in python 
  
import threading 
def gfg(): 
    print("Cafedev\n") 
  
timer = threading.Timer(2.0, gfg) 
timer.start() 
print("Exit\n") 

Kết quả in ra là:

Exit
Cafedev

Giải thích: Đoạn chương trình trên sẽ lập lịch cho hàm gfg() chạy sau khoảng thời gian là 5 giây, kể từ khi hàm start() được gọi.

2. Hủy đi một timer

Cú pháp:

timer.cancel()

Câu lệnh này sẽ dừng timer lại, và hủy việc thực thi  hành động mà timer này đang thực hiện. Câu lệnh này sẽ chỉ làm việc nếu timer vẫn đang ở trong waiting stage – giai đoạn chờ đợi.

Dưới đây là đoạn chương trình Python mô tả cách hủy đi một (đối tượng) timer


# Program to cancel the timer 
import threading 
  
def gfg(): 
    print("GeeksforGeeks\n") 
  
timer = threading.Timer(5.0, gfg) 
timer.start() 
print("Cancelling timer\n") 
timer.cancel() 
print("Exit\n") 

Kết quả in ra là:

Cancelling timer
Exit

Nguồn và Tài liệu tiếng anh tham khảo:

  • w3school
  • python.org
  • geeksforgeeks

Tài liệu từ cafedev:

  • Full series tự học Python từ cơ bản tới nâng cao tại đây nha.
  • Ebook về python tại đây.
  • Các series tự học lập trình khác

Nếu bạn thấy hay và hữu ích, bạn có thể tham gia các kênh sau của cafedev để nhận được nhiều hơn nữa:

  • Group Facebook
  • Fanpage
  • Youtube
  • Instagram
  • Twitter
  • Linkedin
  • Pinterest
  • Trang chủ

Chào thân ái và quyết thắng!

Đăng ký kênh youtube để ủng hộ Cafedev nha các bạn, Thanks you!

I have a code which runs for more than 1,000 iterations. I want te implement a timer that starts before the code starts executing and stops after the execution of the code is done. By this i simply want to measure the time taken for the code to complete the iterations. How do I implement such a timer in python?

Code Structure:

Start timer

//Code

Stop Timer

Thanks in advance!

asked Dec 21, 2014 at 23:35

hnvasahnvasa

7504 gold badges12 silver badges26 bronze badges

0

Timer objects are created using Timer class which is a subclass of the Thread class. Using this class we can set a delay on any action that should be run only after a certain amount of time has passed(timer) and can easily be cancelled during that delay.

Nội dung chính

  • Syntax for creating Timer object
  • Methods of Timer class
  • start() method
  • cancel() method
  • Time for an Example
  • Introduction to Python Threading Timer
  • Syntax of Python Threading Timer
  • Examples of Python Threading Timer
  • Recommended Articles

Timers are started, just like normal threads, by calling their start() method. A timer thread can be stopped (before its action has begun) by calling its cancel() method.

Timer object is generally used to implement scheduled tasks which supposed to be executed only after a certain instant of time.

Also, its not necessary that the Timer object will be executed exactly after the scheduled time as after that the python intrepreter looks for a thread to execute the timer object task, which if not available leads to more waiting.

Syntax for creating Timer object

Following is the syntax for the Timer class constructor:

threading.Timer(interval, function, args=[], kwargs={})

This way we can create a timer object that will run the function with arguments args and keyword arguments kwargs, after interval seconds have passed.

Methods of Timer class

In the Timer class we have two methods used for starting and cancelling the execution of the timer object.


start() method

This method is used to start the execution of the timer object. When we call this method, then the timer object starts its timer.


cancel() method

This method is used to stop the timer and cancel the execution of the timer object's action. This will only work if the timer has not performed its action yet.

Time for an Example

Below we have a simple example where we create a timer object and start it.

import threading def task(): print("timer object task running...") if __name__=='__main__': t = threading.Timer(10, task) t.start() # after 10 seconds, task will be executed

The above program is a simple program, now let's use the cancel method to cancel the timer object task's execution.

In the program above, first comment the code on line number 13 and 14 and run the program, then uncomment those lines and see the cancel() method in action.

Introduction to Python Threading Timer

The timer is a subsidiary class present in the python library named “threading”, which is generally utilized to run a code after a specified time period. Python’s threading.Timer() starts after the delay specified as an argument within the threading. Timer class itself and thus delaying the execution of the subsequent operation by the same duration of time. threading.Timer() class needs to be started explicitly by utilizing the start() function corresponding to that threading.Timer() object. It can also be stopped even before it has started execution by utilizing the cancel() function corresponding to that threading.Timer() object.

Syntax of Python Threading Timer

We need to import the python library “threading” to use the “Timer” function specified in it.

import threading as th

Here we have specified a short name for the library by creating an alias for the same using the “as” keyword. In Short, Aliasing the Python library gives us the capability of utilizing this shorthand notation to call the Timer() class as:

th.Timer()

instead of

threading.Timer()

Timer() classed is specified with multiple arguments, out of which the “Delay Duration / Interval” and the corresponding function that needs to be delayed are quire important ones.

T = th.Timer (Delay Duration, function, args = None, kwargs = None)

  • Delay Durationis the time interval in seconds for which the specified function needs to be delayed.
  • The function is the specified function that needs to be delayed.
  • An empty list will be utilized by default if args is None.
  • An empty dict will be utilized by default if kwargs is None.

Here we are creating a timer object named as “T”, which can be stated explicitly by utilizing.

T.start()

It can also be stopped even before it has started execution by utilizing the cancel() function corresponding to this timer object “T” as:

T.cancel()

Examples of Python Threading Timer

Following are the different examples of the python threading timer.

Example #1

Let’s try to understand its operation with the help of the below Example:

Code:

##Program to demonstrate the usage of threading.Timer() class within Python import threading as th ## Creating a function def prnt(): print("EDU CBA \n") T = th.Timer(3.0, prnt) T.start()

print("Exit Program\n")

Output:

Case 1:

EDU CBA
Exit Program

Case 2:

Exit Program
EDU CBA

Although the “prnt” function is being called even before we are printing the text “Exit Program”, but still results may vary as it’s dependent on multiple factors.

  • As we have used Timer() over here, which will call the “prnt” function after 3.0 seconds once we have explicitly started the timer object “T”.
  • If the program takes more than 3.0 seconds from T.start() till print(“Exit Program\n”), then we will get the output as per Case 1.
  • Otherwise, the output will be as per Case 2.

Example #2

Let’s now discuss the importance of the cancel function available in Timer class with the help of the below example:

Suppose we want to cancel the execution of this time delayed function “prnt” if in case the control reaches the end of the program before that specified delay time (3.0 seconds) itself, once the timer has been started [ T.start() ], then we can place the below statement at the end of the program.

T.cancel()

Or otherwise, if the program takes more than the specified delay time (i.e. 3 seconds in this case), then the cancel statement will act as a redundant one. The reason being, the Delayed function would already have been executed until the control reached the T.cancel() function itself.

Code:

Let's try to execute the below program: ##Program to demonstrate the usage cancel() function within Timer class import threading as th ## Creating a function def prnt(): print("EDU CBA \n") T = th.Timer(3.0, prnt) T.start() print("Exit Program\n")

T.cancel()

Output:

Case 1:

EDU CBA
Exit Program

Case 2:

Exit Program
EDU CBA

Case 3:

EDU CBA

Case 4:

Exit Program

If will think about the permutation and combinations of the outputs presented by the above program, then case 3 is not at all feasible. The reason being the below statement is not at all governed by the Timer object.

print("Exit Program\n")

Case 1 is feasible when the control of the program takes more than the specified delay time (3.0 seconds) itself to reach the below statement, once the timer has been started [ T.start() ]

T.cancel()

Case 2 is feasible when the control of the program takes more than the specified delay time (3.0 seconds) itself to reach the below statement but executes the print(“Exit Program\n”) before that specified delay time (3.0 seconds) once the timer has been started [ T.start() ]

T.cancel()

Case 4 is feasible when the control of the program reaches and executes the cancel() function before that specified delay time (3.0 seconds) once the timer has been started [ T.start() ]

T.cancel()

In this case, the Timer object will be canceled even before it has executed the “prnt” function.

Example #3

Code:

##Program to demonstrate the if cancel() function cancels the start() function or the Timer object itself import threading as th ## Creating a function def prnt(): print("EDU CBA \n") T = th.Timer(3.0, prnt) T.cancel() T.start()

print("Exit Program\n")

Output:

Case 1:

Exit Program
EDU CBA

Case 2:

Exit Program

In this example, we have placed T.cancel() even before we have explicitly called the Timer object using the below statement.

T.start()

The question here is, can a canceled Timer() object “T” be called by using the start() function? What do you think? The answer is No !!! Once the object is canceled. It can not be started. Thus the output will be as per Case 2.

Conclusion

  • The timer is a subsidiary class present in the python library named “threading”, which is generally utilized to run a code after a specified time period.
  • Timer() class needs to be started explicitly by utilizing the start() function corresponding to that threading.Timer() object.
  • It can also be stopped even before it has started execution by utilizing the cancel() function corresponding to that threading.Timer() object.

This is a guide to Python Threading Timer. Here we discuss the Introduction to Python Threading Timer along with different examples and code implementation. You may also look at the following articles to learn more –