timing.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import datetime
  4. from threading import Lock
  5. import time
  6. class Timing:
  7. def __init__(self, sleep_interval=3):
  8. self.task = {}
  9. self.lock = Lock()
  10. self.sleep_interval = sleep_interval
  11. def add_task(self, task_id, name, interval, func, *args, **kwargs):
  12. """
  13. Add a timing task and schedule will execute it.
  14. :param task_id: Unique task id.
  15. :param name: Task name.
  16. :param interval: The interval between the next task execution.
  17. :param func: The function of timing task execution.
  18. :return:
  19. """
  20. if not isinstance(task_id, str):
  21. raise TypeError('task_id must be str')
  22. if not isinstance(interval, int):
  23. raise TypeError('interval must be int')
  24. if interval < 0:
  25. raise ValueError('interval must be bigger than 0')
  26. if not isinstance(func, function):
  27. raise TypeError('func must be func')
  28. self.lock.acquire()
  29. self.task[task_id] = {'name': name, 'interval': interval, 'func': func, 'args': args, 'kwargs': kwargs}
  30. self.lock.release()
  31. def delete_task(self, task_id):
  32. """
  33. Delete the task from schedule by task_id, if exist, return it.
  34. :param task_id: Unique task id.
  35. :return:
  36. """
  37. self.lock.acquire()
  38. if self.task.__contains__(task_id):
  39. element = self.task.pop(task_id)
  40. return element
  41. return None
  42. def sleep(self):
  43. time.sleep(self.sleep_interval)
  44. def run(self):
  45. """
  46. :return:
  47. """
  48. while True:
  49. self.lock.acquire()
  50. for task_id, task_detail in self.task.keys():
  51. now = int(datetime.datetime.now().timestamp() * 1000)
  52. interval = task_detail['interval']
  53. if interval - (now % interval) > 1:
  54. continue
  55. task_detail['func']()
  56. self.sleep()
  57. self.lock.release()