Python a functional method that implements a function that is executed at regular intervals

  • 2020-12-13 19:01:03
  • OfStack

When I was working on the project, I met one problem:

A function needs to be executed once every 3 minutes, so I want to start the program at 15:45, the function to be executed once after 18 minutes at 16:03, the function to be executed again after 60 minutes at 17:03, the next time at 18:03, and so on.

Here is a repackage based on Timer to implement this functionality.


# -*- coding: utf-8 -*-
# ==================================================
#  right  Timer  The purpose of doing the following re-encapsulation is: when a function needs to be spaced out 1 Period of time is 
#  perform 1 The second time, you don't need to call the function  Timer  Do a reinstall boot 
# ==================================================
__author__ = 'liujiaxing'

from threading import Timer
from datetime import datetime

class MyTimer( object ):

 def __init__( self, start_time, interval, callback_proc, args=None, kwargs=None ):

  self.__timer = None
  self.__start_time = start_time
  self.__interval = interval
  self.__callback_pro = callback_proc
  self.__args = args if args is not None else []
  self.__kwargs = kwargs if kwargs is not None else {}

 def exec_callback( self, args=None, kwargs=None ):
  self.__callback_pro( *self.__args, **self.__kwargs )
  self.__timer = Timer( self.__interval, self.exec_callback )
  self.__timer.start()

 def start( self ):
  interval = self.__interval - ( datetime.now().timestamp() - self.__start_time.timestamp() )
  print( interval )
  self.__timer = Timer( interval, self.exec_callback )
  self.__timer.start()

 def cancel( self ):
  self.__timer.cancel() 
  self.__timer = None

class AA:
 def hello( self, name, age ):
  print( "[%s]\thello %s: %d\n" % ( datetime.now().strftime("%Y%m%d %H:%M:%S"), name, age ) )

if __name__ == "__main__":

 aa = AA()
 start = datetime.now().replace( minute=3, second=0, microsecond=0 )
 tmr = MyTimer( start, 60*60, aa.hello, [ "owenliu", 18 ] )
 tmr.start()
 tmr.cancel()

Related articles: