Python Library Task
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

__init__.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. """
  4. task (Task Module)
  5. ==================
  6. **Author:**
  7. * Dirk Alders <sudo-dirk@mount-mockery.de>
  8. **Description:**
  9. This Module supports helpfull classes for queues, tasks, ...
  10. **Submodules:**
  11. * :class:`task.crontab`
  12. * :class:`task.delayed`
  13. * :class:`task.periodic`
  14. * :class:`task.queue`
  15. * :class:`task.threaded_queue`
  16. **Unittest:**
  17. See also the :download:`unittest <../../task/_testresults_/unittest.pdf>` documentation.
  18. """
  19. __DEPENDENCIES__ = []
  20. import logging
  21. import sys
  22. import threading
  23. import time
  24. if sys.version_info >= (3, 0):
  25. from queue import PriorityQueue
  26. from queue import Empty
  27. else:
  28. from Queue import PriorityQueue
  29. from Queue import Empty
  30. try:
  31. from config import APP_NAME as ROOT_LOGGER_NAME
  32. except ImportError:
  33. ROOT_LOGGER_NAME = 'root'
  34. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  35. __DESCRIPTION__ = """The Module {\\tt %s} is designed to help with task issues like periodic tasks, delayed tasks, queues, threaded queues and crontabs.
  36. For more Information read the documentation.""" % __name__.replace('_', '\_')
  37. """The Module Description"""
  38. __INTERPRETER__ = (2, 3)
  39. """The Tested Interpreter-Versions"""
  40. class queue(object):
  41. """Class to execute queued methods.
  42. :param bool expire: The default value for expire. See also :py:func:`expire`.
  43. **Example:**
  44. .. literalinclude:: ../../task/_examples_/queue.py
  45. Will result to the following output:
  46. .. literalinclude:: ../../task/_examples_/queue.log
  47. """
  48. class job(object):
  49. def __init__(self, priority, callback, *args, **kwargs):
  50. self.priority = priority
  51. self.callback = callback
  52. self.args = args
  53. self.kwargs = kwargs
  54. def run(self, queue):
  55. self.callback(queue, *self.args, **self.kwargs)
  56. def __lt__(self, other):
  57. return self.priority < other.priority
  58. def __init__(self, expire=True):
  59. self.__expire = expire
  60. self.__stop = False
  61. self.queue = PriorityQueue()
  62. def clean_queue(self):
  63. """
  64. This Methods removes all jobs from the queue.
  65. .. note:: Be aware that already runnung jobs will not be terminated.
  66. """
  67. while not self.queue.empty():
  68. try:
  69. self.queue.get(False)
  70. except Empty: # This block is hard to reach for a testcase, but is
  71. continue # needed, if the thread runs dry while cleaning the queue.
  72. self.queue.task_done()
  73. def enqueue(self, priority, method, *args, **kwargs):
  74. """
  75. This enqueues a given callback.
  76. :param number priority: The priority indication number of this task. The lowest value will be queued first.
  77. :param method method: Method to be executed
  78. :param args args: Arguments to be given to method
  79. :param kwargs kwargs: Kewordsarguments to be given to method
  80. .. note:: Called method will get this instance as first argument, followed by :py:data:`args` und :py:data:`kwargs`.
  81. """
  82. self.queue.put(self.job(priority, method, *args, **kwargs))
  83. def qsize(self):
  84. return self.queue.qsize()
  85. def run(self):
  86. """
  87. This starts the execution of the queued methods.
  88. """
  89. self.__stop = False
  90. while not self.__stop:
  91. try:
  92. self.queue.get(timeout=0.1).run(self)
  93. except Empty:
  94. if self.__expire:
  95. break
  96. if type(self) is threaded_queue:
  97. self.thread = None
  98. def expire(self):
  99. """
  100. This sets the expire flag. That means that the process will stop after queue gets empty.
  101. """
  102. self.__expire = True
  103. def stop(self):
  104. """
  105. This sets the stop flag. That means that the process will stop after finishing the active task.
  106. """
  107. self.__stop = True
  108. class threaded_queue(queue):
  109. """Class to execute queued methods in a background thread (See also parent :py:class:`queue`).
  110. :param bool expire: The default value for expire. See also :py:func:`queue.expire`.
  111. **Example:**
  112. .. literalinclude:: ../../task/_examples_/threaded_queue.py
  113. Will result to the following output:
  114. .. literalinclude:: ../../task/_examples_/threaded_queue.log
  115. """
  116. def __init__(self, expire=False):
  117. queue.__init__(self, expire=expire)
  118. self.thread = None
  119. def run(self):
  120. if self.thread is None:
  121. self.thread = threading.Thread(target=self._start, args=())
  122. self.thread.daemon = True # Daemonize thread
  123. self.thread.start() # Start the execution
  124. def join(self):
  125. """
  126. This blocks till the queue is empty.
  127. .. note:: If the queue does not run dry, join will block till the end of the days.
  128. """
  129. self.expire()
  130. if self.thread is not None:
  131. self.thread.join()
  132. def stop(self):
  133. queue.stop(self)
  134. self.join()
  135. def _start(self):
  136. queue.run(self)
  137. class periodic(object):
  138. """
  139. :param float cycle_time: Cycle time in seconds -- method will be executed every *cycle_time* seconds
  140. :param method method: Method to be executed
  141. :param args args: Arguments to be given to method
  142. :param kwargs kwargs: Kewordsarguments to be given to method
  143. Class to execute a method cyclicly.
  144. .. note:: Called method will get this instance as first argument, followed by :py:data:`args` und :py:data:`kwargs`.
  145. **Example:**
  146. .. literalinclude:: ../../task/_examples_/periodic.py
  147. Will result to the following output:
  148. .. literalinclude:: ../../task/_examples_/periodic.log
  149. """
  150. def __init__(self, cycle_time, method, *args, **kwargs):
  151. self._lock = threading.Lock()
  152. self._timer = None
  153. self.method = method
  154. self.cycle_time = cycle_time
  155. self.args = args
  156. self.kwargs = kwargs
  157. self._stopped = True
  158. self._last_tm = None
  159. self.dt = None
  160. def join(self, timeout=0.1):
  161. """
  162. This blocks till the cyclic task is terminated.
  163. :param float timeout: Cycle time for checking if task is stopped
  164. .. note:: Using join means that somewhere has to be a condition calling :py:func:`stop` to terminate.
  165. """
  166. while not self._stopped:
  167. time.sleep(timeout)
  168. def run(self):
  169. """
  170. This starts the cyclic execution of the given method.
  171. """
  172. if self._stopped:
  173. self._set_timer(force_now=True)
  174. def stop(self):
  175. """
  176. This stops the execution of any following task.
  177. """
  178. self._lock.acquire()
  179. self._stopped = True
  180. if self._timer is not None:
  181. self._timer.cancel()
  182. self._lock.release()
  183. def _set_timer(self, force_now=False):
  184. """
  185. This sets the timer for the execution of the next task.
  186. """
  187. self._lock.acquire()
  188. self._stopped = False
  189. if force_now:
  190. self._timer = threading.Timer(0, self._start)
  191. else:
  192. self._timer = threading.Timer(self.cycle_time, self._start)
  193. self._timer.start()
  194. self._lock.release()
  195. def _start(self):
  196. tm = time.time()
  197. if self._last_tm is not None:
  198. self.dt = tm - self._last_tm
  199. self._set_timer(force_now=False)
  200. self.method(self, *self.args, **self.kwargs)
  201. self._last_tm = tm
  202. class delayed(periodic):
  203. """Class to execute a method a given time in the future. See also parent :py:class:`periodic`.
  204. :param float time: Delay time for execution of the given method
  205. :param method method: Method to be executed
  206. :param args args: Arguments to be given to method
  207. :param kwargs kwargs: Kewordsarguments to be given to method
  208. **Example:**
  209. .. literalinclude:: ../../task/_examples_/delayed.py
  210. Will result to the following output:
  211. .. literalinclude:: ../../task/_examples_/delayed.log
  212. """
  213. def run(self):
  214. """
  215. This starts the timer for the delayed execution.
  216. """
  217. self._set_timer(force_now=False)
  218. def _start(self):
  219. self.method(*self.args, **self.kwargs)
  220. self.stop()
  221. class crontab(periodic):
  222. """Class to execute a callback at the specified time conditions. See also parent :py:class:`periodic`.
  223. :param accuracy: Repeat time in seconds for background task checking event triggering. This time is the maximum delay between specified time condition and the execution.
  224. :type accuracy: float
  225. **Example:**
  226. .. literalinclude:: ../../task/_examples_/crontab.py
  227. Will result to the following output:
  228. .. literalinclude:: ../../task/_examples_/crontab.log
  229. """
  230. ANY = '*'
  231. """Constant for matching every condition."""
  232. class cronjob(object):
  233. """Class to handle cronjob parameters and cronjob changes.
  234. :param minute: Minute for execution. Either 0...59, [0...59, 0...59, ...] or :py:const:`crontab.ANY` for every Minute.
  235. :type minute: int, list, str
  236. :param hour: Hour for execution. Either 0...23, [0...23, 0...23, ...] or :py:const:`crontab.ANY` for every Hour.
  237. :type hour: int, list, str
  238. :param day_of_month: Day of Month for execution. Either 0...31, [0...31, 0...31, ...] or :py:const:`crontab.ANY` for every Day of Month.
  239. :type day_of_month: int, list, str
  240. :param month: Month for execution. Either 0...12, [0...12, 0...12, ...] or :py:const:`crontab.ANY` for every Month.
  241. :type month: int, list, str
  242. :param day_of_week: Day of Week for execution. Either 0...6, [0...6, 0...6, ...] or :py:const:`crontab.ANY` for every Day of Week.
  243. :type day_of_week: int, list, str
  244. :param callback: The callback to be executed. The instance of :py:class:`cronjob` will be given as the first, args and kwargs as the following parameters.
  245. :type callback: func
  246. .. note:: This class should not be used stand alone. An instance will be created by adding a cronjob by using :py:func:`crontab.add_cronjob()`.
  247. """
  248. class all_match(set):
  249. """Universal set - match everything"""
  250. def __contains__(self, item):
  251. (item)
  252. return True
  253. def __init__(self, minute, hour, day_of_month, month, day_of_week, callback, *args, **kwargs):
  254. self.set_trigger_conditions(minute or crontab.ANY, hour or crontab.ANY, day_of_month or crontab.ANY, month or crontab.ANY, day_of_week or crontab.ANY)
  255. self.callback = callback
  256. self.args = args
  257. self.kwargs = kwargs
  258. self.__last_cron_check_time__ = None
  259. self.__last_execution__ = None
  260. def set_trigger_conditions(self, minute=None, hour=None, day_of_month=None, month=None, day_of_week=None):
  261. """This Method changes the execution parameters.
  262. :param minute: Minute for execution. Either 0...59, [0...59, 0...59, ...] or :py:const:`crontab.ANY` for every Minute.
  263. :type minute: int, list, str
  264. :param hour: Hour for execution. Either 0...23, [0...23, 0...23, ...] or :py:const:`crontab.ANY` for every Hour.
  265. :type hour: int, list, str
  266. :param day_of_month: Day of Month for execution. Either 0...31, [0...31, 0...31, ...] or :py:const:`crontab.ANY` for every Day of Month.
  267. :type day_of_month: int, list, str
  268. :param month: Month for execution. Either 0...12, [0...12, 0...12, ...] or :py:const:`crontab.ANY` for every Month.
  269. :type month: int, list, str
  270. :param day_of_week: Day of Week for execution. Either 0...6, [0...6, 0...6, ...] or :py:const:`crontab.ANY` for every Day of Week.
  271. :type day_of_week: int, list, str
  272. """
  273. if minute is not None:
  274. self.minute = self.__conv_to_set__(minute)
  275. if hour is not None:
  276. self.hour = self.__conv_to_set__(hour)
  277. if day_of_month is not None:
  278. self.day_of_month = self.__conv_to_set__(day_of_month)
  279. if month is not None:
  280. self.month = self.__conv_to_set__(month)
  281. if day_of_week is not None:
  282. self.day_of_week = self.__conv_to_set__(day_of_week)
  283. def __conv_to_set__(self, obj):
  284. if obj is crontab.ANY:
  285. return self.all_match()
  286. elif isinstance(obj, (int, long) if sys.version_info < (3,0) else (int)):
  287. return set([obj])
  288. else:
  289. return set(obj)
  290. def __execution_needed_for__(self, minute, hour, day_of_month, month, day_of_week):
  291. if self.__last_execution__ != [minute, hour, day_of_month, month, day_of_week]:
  292. if minute in self.minute and hour in self.hour and day_of_month in self.day_of_month and month in self.month and day_of_week in self.day_of_week:
  293. return True
  294. return False
  295. def __store_execution_reminder__(self, minute, hour, day_of_month, month, day_of_week):
  296. self.__last_execution__ = [minute, hour, day_of_month, month, day_of_week]
  297. def cron_execution(self, tm):
  298. """This Methods executes the Cron-Callback, if a execution is needed for the given time (depending on the parameters on initialisation)
  299. :param tm: (Current) Time Value to be checked. The time needs to be given in seconds since 1970 (e.g. generated by int(time.time())).
  300. :type tm: int
  301. """
  302. if self.__last_cron_check_time__ is None:
  303. self.__last_cron_check_time__ = tm - 1
  304. #
  305. for t in range(self.__last_cron_check_time__ + 1, tm + 1):
  306. lt = time.localtime(t)
  307. if self.__execution_needed_for__(lt[4], lt[3], lt[2], lt[1], lt[6]):
  308. self.callback(self, *self.args, **self.kwargs)
  309. self.__store_execution_reminder__(lt[4], lt[3], lt[2], lt[1], lt[6])
  310. break
  311. self.__last_cron_check_time__ = tm
  312. def __init__(self, accuracy=30):
  313. periodic.__init__(self, accuracy, self.__periodic__)
  314. self.__crontab__ = []
  315. def __periodic__(self, rt):
  316. (rt)
  317. tm = int(time.time())
  318. for cronjob in self.__crontab__:
  319. cronjob.cron_execution(tm)
  320. def add_cronjob(self, minute, hour, day_of_month, month, day_of_week, callback, *args, **kwargs):
  321. """This Method adds a cronjob to be executed.
  322. :param minute: Minute for execution. Either 0...59, [0...59, 0...59, ...] or :py:const:`crontab.ANY` for every Minute.
  323. :type minute: int, list, str
  324. :param hour: Hour for execution. Either 0...23, [0...23, 0...23, ...] or :py:const:`crontab.ANY` for every Hour.
  325. :type hour: int, list, str
  326. :param day_of_month: Day of Month for execution. Either 0...31, [0...31, 0...31, ...] or :py:const:`crontab.ANY` for every Day of Month.
  327. :type day_of_month: int, list, str
  328. :param month: Month for execution. Either 0...12, [0...12, 0...12, ...] or :py:const:`crontab.ANY` for every Month.
  329. :type month: int, list, str
  330. :param day_of_week: Day of Week for execution. Either 0...6, [0...6, 0...6, ...] or :py:const:`crontab.ANY` for every Day of Week.
  331. :type day_of_week: int, list, str
  332. :param callback: The callback to be executed. The instance of :py:class:`cronjob` will be given as the first, args and kwargs as the following parameters.
  333. :type callback: func
  334. .. note:: The ``callback`` will be executed with it's instance of :py:class:`cronjob` as the first parameter.
  335. """
  336. self.__crontab__.append(self.cronjob(minute, hour, day_of_month, month, day_of_week, callback, *args, **kwargs))