Python Library Task
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 16KB

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