2015-12-31 14:55:15 +01:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# A library that provides a Python interface to the Telegram Bot API
|
2016-01-05 14:12:03 +01:00
|
|
|
# Copyright (C) 2015-2016
|
|
|
|
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
2015-12-31 14:55:15 +01:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser Public License
|
|
|
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
2016-05-26 14:01:59 +02:00
|
|
|
"""This module contains the classes JobQueue and Job."""
|
2015-12-31 14:55:15 +01:00
|
|
|
|
|
|
|
import logging
|
|
|
|
import time
|
2016-09-27 09:21:35 +02:00
|
|
|
import warnings
|
2016-05-25 22:51:13 +02:00
|
|
|
from threading import Thread, Lock, Event
|
2016-06-22 00:24:59 +02:00
|
|
|
from queue import PriorityQueue, Empty
|
2015-12-31 14:55:15 +01:00
|
|
|
|
|
|
|
|
|
|
|
class JobQueue(object):
|
2016-06-21 21:20:57 +02:00
|
|
|
"""This class allows you to periodically perform tasks with the bot.
|
2015-12-31 14:55:15 +01:00
|
|
|
|
|
|
|
Attributes:
|
|
|
|
queue (PriorityQueue):
|
|
|
|
bot (Bot):
|
|
|
|
|
|
|
|
Args:
|
|
|
|
bot (Bot): The bot instance that should be passed to the jobs
|
2016-03-01 19:20:51 +01:00
|
|
|
|
2016-09-27 09:21:35 +02:00
|
|
|
Deprecated: 5.2
|
|
|
|
prevent_autostart (Optional[bool]): Thread does not start during initialisation.
|
|
|
|
Use `start` method instead.
|
2015-12-31 14:55:15 +01:00
|
|
|
"""
|
|
|
|
|
2016-09-27 09:21:35 +02:00
|
|
|
def __init__(self, bot, prevent_autostart=None):
|
|
|
|
if prevent_autostart is not None:
|
|
|
|
warnings.warn("prevent_autostart is being deprecated, use `start` method instead.")
|
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
self.queue = PriorityQueue()
|
|
|
|
self.bot = bot
|
2016-06-21 21:25:15 +02:00
|
|
|
self.logger = logging.getLogger(self.__class__.__name__)
|
2016-06-22 00:24:59 +02:00
|
|
|
self.__start_lock = Lock()
|
|
|
|
self.__next_peek_lock = Lock() # to protect self._next_peek & self.__tick
|
2016-05-25 22:51:13 +02:00
|
|
|
self.__tick = Event()
|
2016-06-22 00:24:59 +02:00
|
|
|
self.__thread = None
|
|
|
|
""":type: Thread"""
|
2016-05-28 13:46:57 +02:00
|
|
|
self._next_peek = None
|
2016-06-22 00:24:59 +02:00
|
|
|
""":type: float"""
|
2016-05-28 13:46:57 +02:00
|
|
|
self._running = False
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
def put(self, job, next_t=None):
|
2016-09-27 09:21:35 +02:00
|
|
|
"""Queue a new job.
|
2015-12-31 14:55:15 +01:00
|
|
|
|
|
|
|
Args:
|
2016-05-25 22:51:13 +02:00
|
|
|
job (Job): The ``Job`` instance representing the new job
|
|
|
|
next_t (Optional[float]): Time in seconds in which the job should be executed first.
|
|
|
|
Defaults to ``job.interval``
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-06-21 21:20:57 +02:00
|
|
|
"""
|
2016-05-25 22:51:13 +02:00
|
|
|
job.job_queue = self
|
2015-12-31 14:55:15 +01:00
|
|
|
|
|
|
|
if next_t is None:
|
2016-05-25 22:51:13 +02:00
|
|
|
next_t = job.interval
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
now = time.time()
|
|
|
|
next_t += now
|
2016-01-04 00:01:00 +01:00
|
|
|
|
2016-06-21 21:20:57 +02:00
|
|
|
self.logger.debug('Putting job %s with t=%f', job.name, next_t)
|
2015-12-31 14:55:15 +01:00
|
|
|
self.queue.put((next_t, job))
|
|
|
|
|
2016-05-26 14:01:59 +02:00
|
|
|
# Wake up the loop if this job should be executed next
|
2016-06-22 00:24:59 +02:00
|
|
|
self._set_next_peek(next_t)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
def _set_next_peek(self, t):
|
|
|
|
"""
|
|
|
|
Set next peek if not defined or `t` is before next peek.
|
|
|
|
In case the next peek was set, also trigger the `self.__tick` event.
|
|
|
|
|
|
|
|
"""
|
|
|
|
with self.__next_peek_lock:
|
|
|
|
if not self._next_peek or self._next_peek > t:
|
|
|
|
self._next_peek = t
|
|
|
|
self.__tick.set()
|
2016-01-05 13:32:19 +01:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
def tick(self):
|
|
|
|
"""
|
2016-06-21 21:20:57 +02:00
|
|
|
Run all jobs that are due and re-enqueue them with their interval.
|
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
"""
|
|
|
|
now = time.time()
|
|
|
|
|
2016-06-21 21:20:57 +02:00
|
|
|
self.logger.debug('Ticking jobs with t=%f', now)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
t, job = self.queue.get(False)
|
|
|
|
except Empty:
|
|
|
|
break
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
self.logger.debug('Peeked at %s with t=%f', job.name, t)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
if t > now:
|
|
|
|
# we can get here in two conditions:
|
|
|
|
# 1. At the second or later pass of the while loop, after we've already processed
|
|
|
|
# the job(s) we were supposed to at this time.
|
|
|
|
# 2. At the first iteration of the loop only if `self.put()` had triggered
|
|
|
|
# `self.__tick` because `self._next_peek` wasn't set
|
|
|
|
self.logger.debug("Next task isn't due yet. Finished!")
|
|
|
|
self.queue.put((t, job))
|
|
|
|
self._set_next_peek(t)
|
|
|
|
break
|
|
|
|
|
|
|
|
if job._remove.is_set():
|
|
|
|
self.logger.debug('Removing job %s', job.name)
|
|
|
|
continue
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
if job.enabled:
|
|
|
|
self.logger.debug('Running job %s', job.name)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
try:
|
|
|
|
job.run(self.bot)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
except:
|
2016-06-24 19:22:49 +02:00
|
|
|
self.logger.exception('An uncaught error was raised while executing job %s',
|
|
|
|
job.name)
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
else:
|
|
|
|
self.logger.debug('Skipping disabled job %s', job.name)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
if job.repeat:
|
|
|
|
self.put(job)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
def start(self):
|
|
|
|
"""
|
2016-01-04 00:01:00 +01:00
|
|
|
Starts the job_queue thread.
|
2016-06-21 21:20:57 +02:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
"""
|
2016-06-22 00:24:59 +02:00
|
|
|
self.__start_lock.acquire()
|
2016-05-26 14:01:59 +02:00
|
|
|
|
2016-05-28 13:46:57 +02:00
|
|
|
if not self._running:
|
|
|
|
self._running = True
|
2016-06-22 00:24:59 +02:00
|
|
|
self.__start_lock.release()
|
|
|
|
self.__thread = Thread(target=self._main_loop, name="job_queue")
|
|
|
|
self.__thread.start()
|
2016-06-21 21:20:57 +02:00
|
|
|
self.logger.debug('%s thread started', self.__class__.__name__)
|
2016-05-26 14:01:59 +02:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
else:
|
2016-06-22 00:24:59 +02:00
|
|
|
self.__start_lock.release()
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-06-22 00:24:59 +02:00
|
|
|
def _main_loop(self):
|
2016-01-04 00:01:00 +01:00
|
|
|
"""
|
2016-05-26 14:01:59 +02:00
|
|
|
Thread target of thread ``job_queue``. Runs in background and performs ticks on the job
|
|
|
|
queue.
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-06-21 21:20:57 +02:00
|
|
|
"""
|
2016-05-28 13:46:57 +02:00
|
|
|
while self._running:
|
2016-06-22 00:24:59 +02:00
|
|
|
# self._next_peek may be (re)scheduled during self.tick() or self.put()
|
|
|
|
with self.__next_peek_lock:
|
|
|
|
tmout = self._next_peek and self._next_peek - time.time()
|
|
|
|
self._next_peek = None
|
2016-05-25 22:51:13 +02:00
|
|
|
self.__tick.clear()
|
2016-06-22 00:24:59 +02:00
|
|
|
|
|
|
|
self.__tick.wait(tmout)
|
|
|
|
|
|
|
|
# If we were woken up by self.stop(), just bail out
|
|
|
|
if not self._running:
|
|
|
|
break
|
2016-05-25 22:51:13 +02:00
|
|
|
|
2016-01-04 00:01:00 +01:00
|
|
|
self.tick()
|
|
|
|
|
2016-06-21 21:20:57 +02:00
|
|
|
self.logger.debug('%s thread stopped', self.__class__.__name__)
|
2016-01-04 01:56:22 +01:00
|
|
|
|
2015-12-31 14:55:15 +01:00
|
|
|
def stop(self):
|
|
|
|
"""
|
|
|
|
Stops the thread
|
|
|
|
"""
|
2016-06-22 00:24:59 +02:00
|
|
|
with self.__start_lock:
|
2016-05-28 13:46:57 +02:00
|
|
|
self._running = False
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
self.__tick.set()
|
2016-06-22 00:24:59 +02:00
|
|
|
if self.__thread is not None:
|
|
|
|
self.__thread.join()
|
2016-05-25 22:51:13 +02:00
|
|
|
|
|
|
|
def jobs(self):
|
|
|
|
"""Returns a tuple of all jobs that are currently in the ``JobQueue``"""
|
|
|
|
return tuple(job[1] for job in self.queue.queue if job)
|
|
|
|
|
|
|
|
|
|
|
|
class Job(object):
|
|
|
|
"""This class encapsulates a Job
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
callback (function):
|
|
|
|
interval (float):
|
|
|
|
repeat (bool):
|
|
|
|
name (str):
|
2016-05-28 13:41:23 +02:00
|
|
|
enabled (bool): Boolean property that decides if this job is currently active
|
2016-05-25 22:51:13 +02:00
|
|
|
|
|
|
|
Args:
|
|
|
|
callback (function): The callback function that should be executed by the Job. It should
|
|
|
|
take two parameters ``bot`` and ``job``, where ``job`` is the ``Job`` instance. It
|
|
|
|
can be used to terminate the job or modify its interval.
|
|
|
|
interval (float): The interval in which this job should execute its callback function in
|
|
|
|
seconds.
|
|
|
|
repeat (Optional[bool]): If this job should be periodically execute its callback function
|
2016-05-26 13:55:30 +02:00
|
|
|
(``True``) or only once (``False``). Defaults to ``True``
|
|
|
|
context (Optional[object]): Additional data needed for the callback function. Can be
|
|
|
|
accessed through ``job.context`` in the callback. Defaults to ``None``
|
2016-05-25 22:51:13 +02:00
|
|
|
|
|
|
|
"""
|
|
|
|
job_queue = None
|
|
|
|
|
2016-05-26 13:55:30 +02:00
|
|
|
def __init__(self, callback, interval, repeat=True, context=None):
|
2016-05-25 22:51:13 +02:00
|
|
|
self.callback = callback
|
|
|
|
self.interval = interval
|
|
|
|
self.repeat = repeat
|
2016-05-26 13:55:30 +02:00
|
|
|
self.context = context
|
2016-05-25 22:51:13 +02:00
|
|
|
|
|
|
|
self.name = callback.__name__
|
|
|
|
self._remove = Event()
|
|
|
|
self._enabled = Event()
|
|
|
|
self._enabled.set()
|
|
|
|
|
2016-05-28 13:41:23 +02:00
|
|
|
def run(self, bot):
|
2016-05-25 22:51:13 +02:00
|
|
|
"""Executes the callback function"""
|
2016-05-28 13:41:23 +02:00
|
|
|
self.callback(bot, self)
|
2016-05-25 22:51:13 +02:00
|
|
|
|
|
|
|
def schedule_removal(self):
|
|
|
|
"""
|
|
|
|
Schedules this job for removal from the ``JobQueue``. It will be removed without executing
|
|
|
|
its callback function again.
|
2016-06-21 21:20:57 +02:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
"""
|
|
|
|
self._remove.set()
|
|
|
|
|
|
|
|
def is_enabled(self):
|
|
|
|
return self._enabled.is_set()
|
|
|
|
|
|
|
|
def set_enabled(self, status):
|
|
|
|
if status:
|
|
|
|
self._enabled.set()
|
|
|
|
else:
|
|
|
|
self._enabled.clear()
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
enabled = property(is_enabled, set_enabled)
|
2015-12-31 14:55:15 +01:00
|
|
|
|
2016-05-25 22:51:13 +02:00
|
|
|
def __lt__(self, other):
|
|
|
|
return False
|