Skip to content

Instantly share code, notes, and snippets.

@Ethan-Zhang
Last active December 29, 2015 07:59
Show Gist options
  • Save Ethan-Zhang/7640380 to your computer and use it in GitHub Desktop.
Save Ethan-Zhang/7640380 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
The KxConfig is a tool for ConfigObj model use in tornado framework with
features of singleton and PeriodicCallback timer.
Here is a simple example:
from tornado import ioloop
from kx_config import KxConfig
def main():
#Create a KxConfig
KxConfig('a.ini')
#Create a KxConfig
KxConfig('a.ini')
#Once created the instance, call the instance() method to acquire
#singleton instance.
#Use KxConfig.instance().configs[name] to read the config item in
#anywhere of the project.
configs = KxConfig.instance()
#start a tornado PeriodCallback timer
configs.start_timer()
ioloop.IOLoop.instance().start()
ioloop.IOLoop.instance().stop()
if __name__ == '__main__':
main()
"""
import os
from configobj import ConfigObj
from tornado import ioloop
class KxConfig(object):
@staticmethod
def instance():
return KxConfig._instance
def __init__(self, path):
self.configs = ConfigObj(path)
self._log_path = path
KxConfig._instance = self
def reload(self):
"""
reload the ini file, if the file modify time has changed
"""
mtime = os.path.getmtime(self._log_path)
if not hasattr(self, '_origin_mtime'):
self._origin_mtime = mtime
if self._origin_mtime != mtime:
self._origin_mtime = mtime
self.configs.reload()
def start_timer(self):
if not hasattr(self, '_reload_timer'):
self._reload_timer = ioloop.PeriodicCallback(self.reload, 5000)
self._reload_timer.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment