【Python】300行代码实现crontab定时器功能 【下】

简介: 熟悉Linux的都知道在Linux下有一个crontab的定时任务,可以很方便的进行各种定时、计划任务的执行。有时候写代码也需要用到定时器业务,因此我使用Python实现了一个类似的定时器模块,可以很方便的做定时业务,使用例子如下
 # 只有满足条件才执行
     if self.call_condition is None or self.call_condition != self.cur_condition:
        self.call_condition = self.cur_condition
        return True
     return False
  def call(self):
     """执行定时回调"""
     try:
        self.call_able(*self.call_args)
     except Exception as e:
        print("call", self.call_able, "error:", e)
  @staticmethod
  def check_target_value(src_value, des_value):
     """检查指定值"""
     return src_value == des_value
  @staticmethod
  def check_delay_value(src_value, des_value):
     """检查每隔多久"""
        return src_value > des_value:
  @staticmethod
  def check_range_value(src_value, min_value, max_value):
     """检查区间"""
     return src_value >= min_value and src_value <= max_value
  @staticmethod
  def check_multi_value(src_value, values):
     """检查多个值"""
     return src_value in values
  @staticmethod
  def _sub_months(st, ed):
     return (ed.year - st.year)*12 + (ed.month - st.month)
  @staticmethod
  def _parse_part(value):
     """解析单个数据"""
     value = value.strip()
     if value == "*":
        return -1, -1
     # 指定时间一次
     if value.isdigit():
        return 0, int(value, 10)
     # */v 每隔多久一次
     fraction_idx = value.find("/")
     if fraction_idx >= 0 :
        denominator = value[fraction_idx + 1:]
        if not denominator.isdigit():
            return -1, -1
        if value.startswith("*"):
           return 1, int(denominator, 10)
        else:
           # 特殊区间A-B/N 每个多久,且在区间A,B内
           range_idx = value.find("-")
           if range_idx < 0:
              return -1, -1
           # 区间 + 间隔
           values = []
           range_values = value[:fraction_idx].split("-")
           if len(range_values) != 2:
              return -1, -1
           # 必须是数字,且只存在2个值
           if range_values[0].isdigit() and range_values[1].isdigit():
              values.append(int(range_values[0], 10))
              values.append(int(range_values[1], 10))
            values.append(int(denominator, 10))
            return 1, values
    # 多个时间点 A,B,...,Z
    dom_idx = value.find(",")
    if dom_idx >= 0:
       values = []
       for v in value.split(","):
           if v.isdigit():
               values.append(int(v, 10))
       return 2, values
     # 区间A-B
     range_idx = value.find("-")
     if range_idx >= 0:
         values = []
         range_values = value.split("-")
         if len(range_values) != 2:
            return -1, -1
         # 必须是数字,且只存在2个值
         if range_values[0].isdigit() and range_values[1].isdigit():
             values.append(int(range_values[0],10))
             values.append(int(range_values[1],10))
             return 3, values
         return -1, -1
    return -1, -1
class Timer:
    def __init__(self, not_thread=False):
        """创建定时器对象"""
        self._thread = None
        self._timer_data = {}
        if not not_thread:
            self._thread = threading.Thread(target=self._update, args=())
            self._thread.start()
    def register(self, time_fmt, call_able, *args):
        """注册定时器"""
        timer_data = TimerInfo(time_fmt, call_able, args)
        if not timer_data.enable:
            return
        timer_id = uuid.uuid4()
        self._timer_data[timer_id] = timer_data
        return timer_id
    def _update(self):
        """内部更新"""
        while self._thread:
            self.update(datetime.datetime.now())
            time.sleep(5)
    def update(self, date_time):
        """外部更新使用"""
        if not isinstance(date_time, datetime.datetime):
            raise TypeError("date_time must be datetime")
        remove_list = []
        for tid, node in self._timer_data.items():
            if not node.enable:
                remove_list.append(tid)
                continue
            if node.on_timer(date_time):
                node.call()
        # 删除已标记删除的定时器列表
        for tid in remove_list:
            del self._timer_data[tid]
    def remove(self, timer_id):
        """移除定时器"""
        if timer_id in self._timer_data:
            # 只标记
            self._timer_data[timer_id].enable = False
相关文章
|
11天前
|
存储 算法 调度
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
112 26
|
14天前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
119 1
|
17天前
|
机器学习/深度学习 算法 调度
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
|
8天前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
197 101
|
8天前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
161 104
|
8天前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
226 99
|
15天前
|
IDE 开发工具 开发者
Python类型注解:提升代码可读性与健壮性
Python类型注解:提升代码可读性与健壮性
189 102
|
15天前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
164 99
|
15天前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
144 98
|
19天前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能

推荐镜像

更多