Add schedule / also for updates

This commit is contained in:
pvizeli 2017-04-03 17:39:00 +02:00
parent ffdbbcc104
commit 7211e6c562
3 changed files with 63 additions and 1 deletions

View File

@ -8,6 +8,8 @@ URL_ADDONS_REPO = 'https://github.com/pvizeli/hassio-addons'
HASSIO_SHARE = "/data"
RUN_UPDATE_INFO_TASKS = 28800
FILE_HASSIO_ADDONS = "{}/addons.json".format(HASSIO_SHARE)
FILE_HASSIO_CONFIG = "{}/config.json".format(HASSIO_SHARE)

View File

@ -8,7 +8,8 @@ import docker
from . import bootstrap
from .api import RestAPI
from .host_controll import HostControll
from .const import SOCKET_DOCKER
from .const import SOCKET_DOCKER, RUN_UPDATE_INFO_TASKS
from .scheduler import Scheduler
from .dock.homeassistant import DockerHomeAssistant
from .dock.supervisor import DockerSupervisor
@ -23,6 +24,7 @@ class HassIO(object):
self.loop = loop
self.websession = aiohttp.ClientSession(loop=self.loop)
self.config = bootstrap.initialize_system_data(self.websession)
self.scheduler = Scheduler(self.loop)
self.api = RestAPI(self.config, self.loop)
self.dock = docker.DockerClient(
base_url="unix:/{}".format(SOCKET_DOCKER), version='auto')
@ -58,6 +60,11 @@ class HassIO(object):
self.api.register_supervisor(self.host_controll)
self.api.register_homeassistant(self.homeassistant)
# schedule update info tasks
self.scheduler.register_task(
self.config.fetch_update_infos, RUN_UPDATE_INFO_TASKS,
first_run=True)
# first start of supervisor?
if self.config.homeassistant_tag is None:
_LOGGER.info("No HomeAssistant docker found.")

View File

@ -0,0 +1,53 @@
"""Schedule for HassIO."""
import asyncio
import logging
_LOGGER = logging.getLogger(__name__)
SEC = 'seconds'
REPEAT = 'repeat'
CALL = 'callback'
TASK = 'task'
class Scheduler(object):
"""Schedule task inside HassIO."""
def __init__(self, loop):
"""Initialize task schedule."""
self.loop = loop
self._data = {}
def register_task(coro_callback, seconds, repeat=True, first_run=False):
"""Schedule a coroutine.
The coroutien need to be a callback without arguments.
"""
idx = hash(coro_callback)
# generate data
opts = {
CALL: coro_callback,
SEC: seconds,
REPEAT: repeat,
}
self._data[idx] = opts
# schedule task
if first_run:
_run_task(idx)
else:
task = self.loop.call_later(seconds, self._run_task, idx)
self._data[idx][TASK] = task
return idx
def _run_task(self, idx):
"""Run a scheduled task."""
data = self._data.pop(idx)
self.loop.create_task(data[CALL]())
if data[REPEAT]:
task = self.loop.call_later(data[SEC], self._run_task, idx)
data[TASK] = task
self._data[idx] = data