Python implements timed tasks

  • 2020-05-24 05:49:15
  • OfStack

There are many ways to implement timed tasks under Python. Here are a few

Circulation sleep:

This is one of the easiest ways to put tasks into a loop and then execute them again over a period of time. The downside is that it's not easy to control, and sleep is a blocking function.


def timer(n): 
  ''''' 
   every n Seconds to perform 1 time  
  ''' 
  while True:  
    print time.strftime('%Y-%m-%d %X',time.localtime())  
    yourTask() #  Here is the task to be performed   
    time.sleep(n)  

threading Timer:

Timer in the threading module helps with timing tasks and is non-blocking.

For example, print helloworld after 3 seconds:


def printHello(): 
  print "hello world" 
 
Timer(3, printHello).start() 

For example, print helloworld once every 3 seconds:


def printHello(): 
  print "Hello World" 
  t = Timer(2, printHello) 
  t.start() 
 
 
if __name__ == "__main__": 
  printHello() 

Using the sched module:

sched is a scheduling (delay processing) mechanism.


# -*- coding:utf-8 -*- 
# use sched to timing 
import time 
import os 
import sched 
 
 
#  Initialize the sched The module scheduler class  
#  The first 1 A parameter is 1 A function that returns a timestamp 2 Three parameters can be blocked before the timer arrives.  
schedule = sched.scheduler(time.time, time.sleep) 
 
 
#  A function triggered by periodic scheduling  
def execute_command(cmd, inc): 
  ''''' 
   The terminal displays the current computer connection  
  ''' 
  os.system(cmd) 
  schedule.enter(inc, 0, execute_command, (cmd, inc)) 
 
 
def main(cmd, inc=60): 
  # enter4 The parameters are: interval event, priority (used for sequencing when two events arriving at the same time are executed at the same time), function triggered by the call,  
  #  The parameter given to the trigger function ( tuple Form)  
  schedule.enter(0, 0, execute_command, (cmd, inc)) 
  schedule.run() 
 
 
#  every 60 Check your network connection in seconds  
if __name__ == '__main__': 
  main("netstat -an", 60) 

Using the timing framework APScheduler:

APScheduler is an Python timing task framework based on Quartz. Tasks are provided based on date, fixed time interval, and crontab types, and can be persisted.

I haven't tried this yet, but I will supplement it after a while.

Timing tasks using windows:

Here you can package the required Python program into an exe file, and then set a timer for execution under windows.


Related articles: