Browse Source

add package timing and config

tangs 6 years ago
parent
commit
8fe14e8e61
3 changed files with 108 additions and 0 deletions
  1. 3 0
      .gitignore
  2. 39 0
      config.py
  3. 66 0
      timing.py

+ 3 - 0
.gitignore

@@ -58,3 +58,6 @@ docs/_build/
 # PyBuilder
 target/
 
+
+.idea
+test

+ 39 - 0
config.py

@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+# -*- coding:utf-8 -*-
+
+import json
+import logging
+import redis
+
+
+class Config:
+    local_config = None
+    redis_config = None
+
+    def __init__(self, path):
+        self.path = path
+
+    def read_local_config(self):
+        try:
+            f = open(self.path)
+            self.local_config = json.load(f)
+        except Exception as e:
+            logging.error("[CONFIG] read config with path: %s error: %s", self.path, e)
+
+    def read_redis_config(self):
+        if self.local_config is None:
+            return None
+
+        host = self.local_config["redis_host"]
+        port = self.local_config["redis_port"]
+        db = self.local_config['redis_db']
+        password = self.local_config['redis_password']
+
+        try:
+            r = redis.Redis(host, port, db=db, password=password)
+            config = r.get('config').decode('utf8')
+            if config is None or config is "":
+                return
+            self.redis_config = json.loads(config)
+        except Exception as e:
+            print(e)

+ 66 - 0
timing.py

@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+# -*- coding:utf-8 -*-
+import datetime
+from threading import Lock
+
+import time
+
+
+class Timing:
+    def __init__(self, sleep_interval=3):
+        self.task = {}
+        self.lock = Lock()
+        self.sleep_interval = sleep_interval
+
+    def add_task(self, task_id, name, interval, func, *args, **kwargs):
+        """
+        Add a timing task and schedule will execute it.
+        :param task_id: Unique task id.
+        :param name: Task name.
+        :param interval: The interval between the next task execution.
+        :param func: The function of timing task execution.
+        :return:
+        """
+        if not isinstance(task_id, str):
+            raise TypeError('task_id must be str')
+        if not isinstance(interval, int):
+            raise TypeError('interval must be int')
+        if interval < 0:
+            raise ValueError('interval must be bigger than 0')
+        if not isinstance(func, function):
+            raise TypeError('func must be func')
+
+        self.lock.acquire()
+        self.task[task_id] = {'name': name, 'interval': interval, 'func': func, 'args': args, 'kwargs': kwargs}
+        self.lock.release()
+
+    def delete_task(self, task_id):
+        """
+        Delete the task from schedule by task_id, if exist, return it.
+        :param task_id: Unique task id.
+        :return:
+        """
+        self.lock.acquire()
+        if self.task.__contains__(task_id):
+            element = self.task.pop(task_id)
+            return element
+        return None
+
+    def sleep(self):
+        time.sleep(self.sleep_interval)
+
+    def run(self):
+        """
+        :return:
+        """
+        while True:
+            self.lock.acquire()
+            for task_id, task_detail in self.task.keys():
+                now = int(datetime.datetime.now().timestamp() * 1000)
+                interval = task_detail['interval']
+                if interval - (now % interval) > 1:
+                    continue
+                task_detail['func']()
+
+            self.sleep()
+            self.lock.release()