Method of Realizing Timing Program by Python

  • 2021-11-13 08:32:11
  • OfStack

Directory timer concept
Realize a simple timing program
Option 1
Option 2

Timer concept

What is a timer? It refers to from the specified time, after a specified time, and then trigger an event, the user can customize the timer cycle and frequency.

Realize a simple timing program

Option 1

How to define a timer function in Python? Let's look at the first method first. Suppose we need to execute a function userCountFunc, which needs to be executed every 1 hour. Well, we can write this:


def main():
    startCronTask(userCountFunc, minutes=60)

if __name__ == '__main__':
    main()

As in the above code, after defining an main function, we define a timing function startCronTask. The first argument is the function name, the second argument is the time, and the second argument indicates how long the function with the first argument will be called. Note that the first parameter is a function object, pass the parameters, and use the function name (such as userCountFunc) to represent the object, not the function execution statement userCountFunc (), otherwise an error will be reported. Then, when implementing this function, it is necessary to introduce timing function. There is a timing task module BlockingScheduler in Python:


from apscheduler.schedulers.blocking import BlockingScheduler

def startCronTask(task, **config):
    # BlockingScheduler
    scheduler = BlockingScheduler()
    scheduler.add_job(task, 'interval', **config)
    scheduler.start()

After defining a scheduling module, the actual timing scheduling function is completed. Next, you need to implement the logic function userCountFunc that executes regularly:


def userCountFunc():
    logger.info('count user')
    ...

In this way, for Scheme 1, the simple timing function is completed.

Option 2

Scheme 1 introduces the BlockingScheduler module of Python. In Python, besides BlockingScheduler, the timer timer can be realized through threads to simply look at the code:


import threading

def timerFunc():
    print('Hello World~')

timer = threading.Timer(1, timerFunc)
timer.start()

In the above code, the timer function threading. Timer mainly has two parameters, and the meaning of the parameters is similar to that of scenario 1. Next, execute this program:

Hello World~

Process finished with exit code 0

We found that the program ended after only executing it once, but it was obviously not the result we wanted. Actually, let's look at the Time class, and there is an explanatory note like this: Call a function after a specified number of seconds. We find that the above is not executed cyclically after execution, so we need to modify it as follows:


import threading

def timerFunc():
    print('Hello World~')
    global timer
    timer = threading.Timer(10.5, timerFunc)
    timer.start()

timer = threading.Timer(3, timerFunc)
timer.start()

At this point, we can see the output:

Hello World~

Hello World~

Hello World~
...

It should be noted here that the timer must be constructed repeatedly within the timer execution function, because the timer is only executed once after construction, and must be called cyclically.

In addition, in the above code, we can actually see that threading. Timer (5.5, timerFunc), the timer interval unit is seconds, which can be floating-point numbers, such as 5.5, 0.9, etc., and the values given inside and outside the execution function timerFunc can be different. As in the above example, the first execution of timerFunc is after 3 seconds, and the subsequent execution is after 10.5 seconds.

Next, let's look at how to end the timing function at another fixed time. We can use cancel to stop the timer from working, as shown in the following example:


import threading

def timerFunc():
    print('Hello World~')
    global timer
    timer = threading.Timer(10.5, timerFunc)
    timer.start()

timer = threading.Timer(3, timerFunc)
timer.start()

time.sleep(60)
timer.cancel()

The above code indicates that after the timer is executed according to 1 fixed time, the execution process takes 60 seconds to stop the timing operation function and exit. The result is displayed as follows:

Hello World~

Hello World~

Hello World~

Hello World~

Hello World~
...

Process finished with exit code 0


Related articles: