[modules/various] Use new interval mechanism

Use generic interval mechanism in most of the modules that use slow
updates.

Only exception: getcrypto, as the interval is specified in seconds there
and I want to retain backwards-compatibility.

fixes #220
This commit is contained in:
Tobias Witek 2018-01-07 20:27:11 +01:00
parent 776be11137
commit 3638aa2420
7 changed files with 55 additions and 79 deletions

View file

@ -20,7 +20,6 @@ Note: source and destination names right now must correspond to the names used b
import bumblebee.input import bumblebee.input
import bumblebee.output import bumblebee.output
import bumblebee.engine import bumblebee.engine
import time
try: try:
import requests import requests
except ImportError: except ImportError:
@ -38,7 +37,7 @@ class Module(bumblebee.engine.Module):
bumblebee.output.Widget(full_text=self.price) bumblebee.output.Widget(full_text=self.price)
) )
self._data = [] self._data = []
self._interval = int(self.parameter("interval", 1)) self.interval(1)
self._base = self.parameter("source", "GBP") self._base = self.parameter("source", "GBP")
self._symbols = self.parameter("destination", "USD,EUR").split(",") self._symbols = self.parameter("destination", "USD,EUR").split(",")
self._nextcheck = 0 self._nextcheck = 0
@ -57,16 +56,13 @@ class Module(bumblebee.engine.Module):
return basefmt.format(SYMBOL[self._base] if self._base in SYMBOL else self._base, ratefmt.join(rates)) return basefmt.format(SYMBOL[self._base] if self._base in SYMBOL else self._base, ratefmt.join(rates))
def update(self, widgets): def update(self, widgets):
timestamp = int(time.time()) self._data = []
if self._nextcheck < timestamp: for symbol in self._symbols:
self._data = [] url = API_URL.format(self._base, symbol)
self._nextcheck = timestamp + self._interval*60 try:
for symbol in self._symbols: response = requests.get(url).json()
url = API_URL.format(self._base, symbol) self._data.append((symbol, response['data']['exchangeRate']))
try: except Exception:
response = requests.get(url).json() pass
self._data.append((symbol, response['data']['exchangeRate']))
except Exception:
pass
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

View file

@ -6,11 +6,10 @@ Requires the following executable:
* dnf * dnf
Parameters: Parameters:
* dnf.interval: Time in seconds between two consecutive update checks (defaulst to 1800) * dnf.interval: Time in seconds between two consecutive update checks (defaulst to 30 minutes)
""" """
import time
import threading import threading
import bumblebee.util import bumblebee.util
@ -53,7 +52,7 @@ class Module(bumblebee.engine.Module):
def __init__(self, engine, config): def __init__(self, engine, config):
widget = bumblebee.output.Widget(full_text=self.updates) widget = bumblebee.output.Widget(full_text=self.updates)
super(Module, self).__init__(engine, config, widget) super(Module, self).__init__(engine, config, widget)
self._next_check = 0 self.interval(30)
def updates(self, widget): def updates(self, widget):
result = [] result = []
@ -62,11 +61,8 @@ class Module(bumblebee.engine.Module):
return "/".join(result) return "/".join(result)
def update(self, widgets): def update(self, widgets):
if int(time.time()) < self._next_check:
return
thread = threading.Thread(target=get_dnf_info, args=(widgets[0],)) thread = threading.Thread(target=get_dnf_info, args=(widgets[0],))
thread.start() thread.start()
self._next_check = int(time.time()) + self.parameter("interval", 30*60)
def state(self, widget): def state(self, widget):
cnt = 0 cnt = 0

View file

@ -10,7 +10,6 @@ Parameters:
* github.interval: Interval in minutes * github.interval: Interval in minutes
""" """
import time
import functools import functools
import bumblebee.input import bumblebee.input
import bumblebee.output import bumblebee.output
@ -27,8 +26,7 @@ class Module(bumblebee.engine.Module):
bumblebee.output.Widget(full_text=self.github) bumblebee.output.Widget(full_text=self.github)
) )
self._count = 0 self._count = 0
self._interval = int(self.parameter("interval", "5")) self.interval(5)
self._nextcheck = 0
self._requests = requests.Session() self._requests = requests.Session()
self._requests.headers.update({"Authorization":"token {}".format(self.parameter("token", ""))}) self._requests.headers.update({"Authorization":"token {}".format(self.parameter("token", ""))})
engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE, engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,
@ -41,23 +39,20 @@ class Module(bumblebee.engine.Module):
return str(self._count) return str(self._count)
def update(self, _, immediate=False): def update(self, _, immediate=False):
if immediate or self._nextcheck < int(time.time()): try:
self._nextcheck = int(time.time()) + self._interval * 60 self._count = 0
url = "https://api.github.com/notifications"
while True:
notifications = self._requests.get(url)
self._count += len(list(filter(lambda notification: notification['unread'], notifications.json())))
next_link = notifications.links.get('next')
if next_link is not None:
url = next_link.get('url')
else:
break
try: except Exception:
self._count = 0 self._count = "n/a"
url = "https://api.github.com/notifications"
while True:
notifications = self._requests.get(url)
self._count += len(list(filter(lambda notification: notification['unread'], notifications.json())))
next_link = notifications.links.get('next')
if next_link is not None:
url = next_link.get('url')
else:
break
except Exception:
self._count = "n/a"
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

View file

@ -8,7 +8,6 @@ Parameters:
* hipchat.interval: Refresh interval in minutes (defaults to 5) * hipchat.interval: Refresh interval in minutes (defaults to 5)
""" """
import time
import functools import functools
import bumblebee.input import bumblebee.input
import bumblebee.output import bumblebee.output
@ -27,8 +26,7 @@ class Module(bumblebee.engine.Module):
bumblebee.output.Widget(full_text=self.output) bumblebee.output.Widget(full_text=self.output)
) )
self._count = 0 self._count = 0
self._interval = int(self.parameter("interval", "5")) self.interval(5)
self._nextcheck = 0
self._requests = requests.Session() self._requests = requests.Session()
self._requests.headers.update({"Authorization":"Bearer {}".format(self.parameter("token", ""))}) self._requests.headers.update({"Authorization":"Bearer {}".format(self.parameter("token", ""))})
@ -40,16 +38,12 @@ class Module(bumblebee.engine.Module):
return str(self._count) return str(self._count)
def update(self, _, immediate=False): def update(self, _, immediate=False):
if immediate or self._nextcheck < int(time.time()): try:
self._nextcheck = int(time.time()) + self._interval * 60 self._count = 0
items = self._requests.get(HIPCHAT_API_URL).json().get('items')
try: self._count = sum([item.get('unreadCount').get('count') for item in items])
self._count = 0
items = self._requests.get(HIPCHAT_API_URL).json().get('items')
self._count = sum([item.get('unreadCount').get('count') for item in items])
except Exception:
self._count = "n/a"
except Exception:
self._count = "n/a"
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

View file

@ -6,7 +6,7 @@ Requires the following executable:
* ping * ping
Parameters: Parameters:
* ping.interval: Time in seconds between two RTT checks (defaults to 60) * ping.ping_interval: Time in seconds between two RTT checks (defaults to 60)
* ping.address : IP address to check * ping.address : IP address to check
* ping.timeout : Timeout for waiting for a reply (defaults to 5.0) * ping.timeout : Timeout for waiting for a reply (defaults to 5.0)
* ping.probes : Number of probes to send (defaults to 5) * ping.probes : Number of probes to send (defaults to 5)
@ -51,7 +51,7 @@ class Module(bumblebee.engine.Module):
super(Module, self).__init__(engine, config, widget) super(Module, self).__init__(engine, config, widget)
widget.set("address", self.parameter("address", "8.8.8.8")) widget.set("address", self.parameter("address", "8.8.8.8"))
widget.set("interval", self.parameter("interval", 60)) widget.set("interval", self.parameter("ping_interval", 60))
widget.set("rtt-probes", self.parameter("probes", 5)) widget.set("rtt-probes", self.parameter("probes", 5))
widget.set("rtt-timeout", self.parameter("timeout", 5.0)) widget.set("rtt-timeout", self.parameter("timeout", 5.0))
widget.set("rtt-avg", 0.0) widget.set("rtt-avg", 0.0)

View file

@ -31,6 +31,7 @@ class Module(bumblebee.engine.Module):
self._currencies = self.parameter('currencies', None) self._currencies = self.parameter('currencies', None)
self._baseurl = 'http://download.finance.yahoo.com/d/quotes.csv' self._baseurl = 'http://download.finance.yahoo.com/d/quotes.csv'
self._value = self.fetch() self._value = self.fetch()
self.interval(60)
if not self._currencies: if not self._currencies:
self._currencies = '$' * len(self._symbols) self._currencies = '$' * len(self._symbols)

View file

@ -7,7 +7,6 @@ Requires the following python packages:
* requests * requests
Parameters: Parameters:
* weather.interval: Interval (in minutes) for updating weather information
* weather.location: Set location (ISO 3166 country code), defaults to 'auto' for getting location from http://ipinfo.io * weather.location: Set location (ISO 3166 country code), defaults to 'auto' for getting location from http://ipinfo.io
* weather.unit: metric (default), kelvin, imperial * weather.unit: metric (default), kelvin, imperial
* weather.apikey: API key from http://api.openweathermap.org * weather.apikey: API key from http://api.openweathermap.org
@ -18,7 +17,6 @@ import bumblebee.output
import bumblebee.engine import bumblebee.engine
import re import re
import json import json
import time
try: try:
import requests import requests
from requests.exceptions import RequestException from requests.exceptions import RequestException
@ -34,10 +32,9 @@ class Module(bumblebee.engine.Module):
self._apikey = self.parameter("apikey", "af7bfe22287c652d032a3064ffa44088") self._apikey = self.parameter("apikey", "af7bfe22287c652d032a3064ffa44088")
self._location = self.parameter("location", "auto") self._location = self.parameter("location", "auto")
self._city = self.parameter("location", "") self._city = self.parameter("location", "")
self._interval = int(self.parameter("interval", "15"))
self._unit = self.parameter("unit", "metric") self._unit = self.parameter("unit", "metric")
self._nextcheck = 0
self._valid = False self._valid = False
self.interval(15)
def _unit_suffix(self): def _unit_suffix(self):
if self._unit == "metric": if self._unit == "metric":
@ -82,27 +79,24 @@ class Module(bumblebee.engine.Module):
return [] return []
def update(self, widgets): def update(self, widgets):
timestamp = int(time.time()) try:
if self._nextcheck < timestamp: weather_url = "http://api.openweathermap.org/data/2.5/weather?appid={}".format(self._apikey)
try: weather_url = "{}&units={}".format(weather_url, self._unit)
self._nextcheck = timestamp + self._interval*60 if self._location == "auto":
weather_url = "http://api.openweathermap.org/data/2.5/weather?appid={}".format(self._apikey) location_url = "http://ipinfo.io/json"
weather_url = "{}&units={}".format(weather_url, self._unit) location = json.loads(requests.get(location_url).text)
if self._location == "auto": coord = location["loc"].split(",")
location_url = "http://ipinfo.io/json" self._city = location["city"]
location = json.loads(requests.get(location_url).text) weather_url = "{url}&lat={lat}&lon={lon}".format(url=weather_url, lat=coord[0], lon=coord[1])
coord = location["loc"].split(",") else:
self._city = location["city"] weather_url = "{url}&q={city}".format(url=weather_url, city=self._location)
weather_url = "{url}&lat={lat}&lon={lon}".format(url=weather_url, lat=coord[0], lon=coord[1]) weather = json.loads(requests.get(weather_url).text)
else: self._temperature = int(weather['main']['temp'])
weather_url = "{url}&q={city}".format(url=weather_url, city=self._location) self._weather = weather['weather'][0]['main'].lower()
weather = json.loads(requests.get(weather_url).text) self._valid = True
self._temperature = int(weather['main']['temp']) except RequestException:
self._weather = weather['weather'][0]['main'].lower() self._valid = False
self._valid = True except Exception:
except RequestException: self._valid = False
self._valid = False
except Exception:
self._valid = False
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4