Improve appdaemon timers a bit

This commit is contained in:
Thomas Lovén 2018-12-26 23:27:24 +01:00
parent 06e4fbcbdb
commit 611a86d017
3 changed files with 62 additions and 10 deletions

40
appdaemon/apps/base.py Normal file
View File

@ -0,0 +1,40 @@
import appdaemon.plugins.hass.hassapi as hass
class Base(hass.Hass):
def initialize(self):
if(getattr(super(), 'initialize', False)):
super().initialize()
class Timers(Base):
def initialize(self):
if(getattr(super(), 'initialize', False)):
super().initialize()
self._timers = {}
functions = [ 'run_in', 'run_once', 'run_at', 'run_daily',
'run_hourly', 'run_minutely', 'run_every', 'run_at_sunrise',
'run_at_sunset' ]
for f in functions:
self.override(f)
setattr(self, '_cancel_timer', super().cancel_timer)
def cancel_timer(self, name, *args, **kwargs):
if type(name) is str:
if name in self._timers:
return super().cancel_timer(self._timers[name])
else:
return super().cancel_timer(*args, **kwargs)
def override(self, f):
setattr(self, f'_{f}', getattr(self, f))
def fn(name, *args, **kwargs):
if type(name) is str:
if name in self._timers:
super().cancel_timer(self._timers[name])
self._timers[name] = getattr(self, f'_{f}')(*args, **kwargs)
return self._timers[name]
else:
return getattr(self, f'_{f}')(name, *args, **kwargs)
setattr(self, f, fn)

View File

@ -1,12 +1,19 @@
import appdaemon.plugins.hass.hassapi as hass import base
#
# Hellow World App
#
# Args:
#
class HelloWorld(hass.Hass): class HelloWorld(base.Timers):
def initialize(self): def initialize(self):
super().initialize()
self.log("Hello from AppDaemon") self.log("Hello from AppDaemon")
self.log("You are now ready to run Apps!") self.log("You are now ready to run Apps!")
self.run_in('test1', self.after_time, 3)
self.run_in('test2', self.after_time2, 5)
self.run_in(self.after_time2, 7)
self.cancel_timer('test2')
def after_time(self, kwargs):
self.log("Running function")
def after_time2(self, kwargs):
self.log("Running function2")

View File

@ -1,4 +1,9 @@
global_modules:
- base
hello_world: hello_world:
global_dependencies:
- base
module: hello module: hello
class: HelloWorld class: HelloWorld