Home Backend Development Python Tutorial Implementing timed loop execution of tasks through Python3

Implementing timed loop execution of tasks through Python3

Apr 19, 2019 pm 01:15 PM
python3 threading time

In our actual development, there is often such a requirement: a certain functional module or task is required to be executed cyclically within the same time period. There is a concept of a timer here. Specifically, how should we implement a timer? Timers have many very practical functions, which can control the execution of threads, reduce system consumption, etc. Now let's practice implementing the timing function in Python3.

Implementing timed loop execution of tasks through Python3

For example, when using Python to develop a crawler system, you may need to perform tasks repeatedly at intervals, so as to implement a thread service to monitor data in the background. The crawling status, the timer can help here.

[Video recommendation: Python3 video tutorial]

[Manual recommendation: Python Chinese Manual]

Through Python documentation We can find threading.Timer() to implement the timing function:

Simple implementation code:

import threading
def func1(a):
    #Do something
    print('Do something')
    a+=1
    print(a)
    print('当前线程数为{}'.format(threading.activeCount()))
    if a>5:
        return
    t=threading.Timer(5,func1,(a,))
    t.start()
Copy after login

Rendering:

Implementing timed loop execution of tasks through Python3

By consulting the information, Python can be used to implement three different scheduled task execution methods:

1. Scheduled task code

#!/user/bin/env python
#定时执行任务命令
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
  os.system(cmd)
  print('task')
def timming_exe(cmd,inc=60):
  schedule.enter(inc,0,perform_command,(cmd,inc))
  schedule.run()
print('show time after 2 seconds:')
timming_exe('echo %time%',2)
Copy after login

2. Periodic execution of tasks

#!/user/bin/env python
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
  #在inc秒后再次运行自己,即周期运行
  schedule.enter(inc, 0, perform_command, (cmd, inc))
  os.system(cmd)
def timming_exe(cmd,inc=60):
  schedule.enter(inc,0,perform_command,(cmd,inc))
  schedule.run()#持续运行,直到计划时间队列变成空为止
print('show time after 2 seconds:')
timming_exe('echo %time%',2)
Copy after login

3 .Loop execution command

#!/user/bin/env python
import time,os
def re_exe(cmd,inc = 60):
  while True:
    os.system(cmd)
    time.sleep(inc)
re_exe("echo %time%",5)
Copy after login

In summary: Python’s methods of implementing timers are all based on schedule and threading, and the specific usage must be flexibly used according to the actual situation.

The two most commonly used modules: threading, Sched

threading module usage:

import threading ,time
from time import sleep, ctime
class Timer(threading.Thread):
        """
        very simple but useless timer.
        """
        def __init__(self, seconds):
                self.runTime = seconds
                threading.Thread.__init__(self)
        def run(self):
                time.sleep(self.runTime)
                print ("Buzzzz!! Time's up!")
class CountDownTimer(Timer):
        """
        a timer that can counts down the seconds.
        """
        def run(self):
                counter = self.runTime
                for sec in range(self.runTime):
                        print (counter)
                        time.sleep(1.0)
                        counter -= 1
                print ("Done")
 
class CountDownExec(CountDownTimer):
        """
        a timer that execute an action at the end of the timer run.
        """
        def __init__(self, seconds, action, args=[]):
                self.args = args
                self.action = action
                CountDownTimer.__init__(self, seconds)
        def run(self):
                CountDownTimer.run(self)
                self.action(self.args)
 
def myAction(args=[]):
        print ("Performing my action with args:")
        print (args)
 
if __name__ == "__main__":
        t = CountDownExec(3, myAction, ["hello", "world"])
        t.start()
        print("2333")
Copy after login

Sched module usage:

'''
使用sched模块实现的timer,sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,
可以使用while循环的方式不停的调用该方法
'''
import time, sched
#被调度触发的函数
def event_func(msg):
    print("Current Time:", time.strftime("%y-%m-%d %H:%M:%S"), 'msg:', msg)
def run_function():
    #初始化sched模块的scheduler类
    s = sched.scheduler(time.time, time.sleep)
    #设置一个调度,因为time.sleep()的时间是一秒,所以timer的间隔时间就是sleep的时间,加上enter的第一个参数
    s.enter(0, 2, event_func, ("Timer event.",))
    s.run()
def timer1():
    while True:
        #sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,可以使用while循环的方式不停的调用该方法
        time.sleep(1)
        run_function()
if __name__ == "__main__":
    timer1()
Copy after login

The above is the detailed content of Implementing timed loop execution of tasks through Python3. 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)

Monotonic clock processing of time package Monotonic clock processing of time package Aug 04, 2023 pm 05:45 PM

Today we are mainly going to take a look at the time application method of golang time package. The general rule between the two is that "wall time" is used to tell time, and "monotonic clock" is used to measure time; there are other clock processing methods.

How to use Java8 Time API How to use Java8 Time API Apr 28, 2023 pm 12:25 PM

1. Overview As part of this article, let us start with some problems with the existing Date and CalendarAPI and explore how the new Java8Date and TimeAPI solve these problems. We will also take a look at the core classes in the Java8 time class library, such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration and their APIs. 2. The problem of thread safety of the old time API (before Java 8)-Date and Calendar classes are not thread-safe, making it difficult for developers to debug concurrency problems of these APIs and need to write additional code to deal with them.

What is the difference and usage between time and datetime in python What is the difference and usage between time and datetime in python May 02, 2023 am 11:01 AM

1. Two ways to represent time in Python: timestamp: offset in seconds relative to 1970.1.100:00:00, unique time tuple struct_time: a total of 9 elements>tm_year: year 1-12> tm_mon: month 1-12>tm_mday: day 1-31>tm_hour: hour 0-23>tm_min: minute 0-59>tm_sec: second 0-59>tm_wday: week 0-6 (0 means Sunday)>tm_day: Day of the year 1-366>tm_isdst: whether it is daylight saving, the default is -1.ti

How to obtain and convert time in Python time module How to obtain and convert time in Python time module May 13, 2023 pm 12:19 PM

Pythontime module time acquisition and conversion Python's Time library can perform time-related processing, such as accessing the current date and time, outputting time in different formats, and waiting for a specified time. 1. Get the time 1.1. Timestamp importtimetimestamp=time.time()#1682737552.5009851 Greenwich Mean Time (GMT) The total number of seconds from 00:00:00 on January 1, 1970 to the present 1.2. Structured time importtimestruct_time= time.localtime()#time.struct_time(tm_year=2

How to use the threading module to create and manage threads in Python 3.x How to use the threading module to create and manage threads in Python 3.x Aug 04, 2023 am 10:37 AM

Introduction to how to use the threading module to create and manage threads in Python 3.x: With the powerful performance of computers, multi-threading has become a common method of parallel processing. In Python's standard library, there is a convenient module - threading. This article will introduce how to use the threading module in Python3.x to create and manage threads, and use code examples to illustrate. 1. What is a thread? A thread is an independent process that executes within a single process.

How to install pip in python3 How to install pip in python3 Dec 20, 2023 pm 05:42 PM

Installation steps: 1. Make sure that Python3 has been installed and can be accessed through the command line; 2. Open the terminal and enter the "python3 -m ensurepip --upgrade" command to install pip; 3. Download the pip installation package from the official Python website; 4. Extract the downloaded pip installation package into a directory; 5. Open the terminal and navigate to the decompressed pip directory; 6. Run the "python3 setup.py install" command to install pip.

Use the PHP function 'time' to return the current UNIX timestamp Use the PHP function 'time' to return the current UNIX timestamp Jul 25, 2023 pm 04:42 PM

Use the PHP function "time" to return the current UNIX timestamp. The UNIX timestamp refers to the total number of seconds since 0:00:00 on January 1, 1970 Coordinated Universal Time (UTC). In PHP, you can use the built-in function "time" to get the current UNIX timestamp. This article explains how to use this function and provides corresponding code examples. Code example: <?php$timestamp=time();echo" current

How to solve 'undefined: time.After' error in golang? How to solve 'undefined: time.After' error in golang? Jun 25, 2023 pm 05:28 PM

Golang is a very popular programming language. Its easy-to-learn, efficient and fast features attract more and more developers. But during use, you will inevitably encounter some problems and errors. For example, when using the After method in the time package, you may encounter an error of undefined: time.After. This article will introduce how to solve this error. Understand the cause of the error In Golang, if we use an unexported function name or incorrect

See all articles