1 # Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 Concurrent networking library - Eventlet, based utilities classes.
19 from ryu.lib import hub
22 LOG = logging.getLogger('utils.evtlet')
25 class EventletIOFactory(object):
28 def create_custom_event():
29 LOG.debug('Create CustomEvent called')
33 def create_looping_call(funct, *args, **kwargs):
34 LOG.debug('create_looping_call called')
35 return LoopingCall(funct, *args, **kwargs)
38 # TODO: improve Timer service and move it into framework
39 class LoopingCall(object):
40 """Call a function repeatedly.
43 def __init__(self, funct, *args, **kwargs):
49 self._self_thread = None
61 # Schedule next iteration of the call.
62 self._self_thread = hub.spawn_after(self._interval, self)
63 self._funct(*self._args, **self._kwargs)
65 def start(self, interval, now=True):
66 """Start running pre-set function every interval seconds.
69 raise ValueError('interval must be >= 0')
75 self._interval = interval
77 self._self_thread = hub.spawn_after(0, self)
79 self._self_thread = hub.spawn_after(self._interval, self)
82 """Stop running scheduled function.
85 if self._self_thread is not None:
86 self._self_thread.cancel()
87 self._self_thread = None
90 """Skip the next iteration and reset timer.
92 if self._self_thread is not None:
93 # Cancel currently scheduled call
94 self._self_thread.cancel()
95 self._self_thread = None
97 self._self_thread = hub.spawn_after(self._interval, self)