def __watch_and_store_partitions(self):
"""
Flush all the dirty partitions to the backend store. This methods gets called periodically on a timer
:return:
"""
logging.debug("checking for dirty partitions in cache: {} found".format(len(self.__dirty_partitions)))
while self.__dirty_partitions:
pid = self.__dirty_partitions.pop()
logging.warning("flushing modified partition {} from cache to mgmt container {}".format(pid,
self.partitionStore.containerNameSdosMgmt))
try:
self.partitionStore.writePartition(pid, io.BytesIO(self.partitionCache[pid]))
except Exception:
self.__dirty_partitions.add(pid)
logging.exception(
"storing changed partition {} failed! {} dirty partitions left to store. Leaving this execution.".format(
pid, len(self.__dirty_partitions)))
break
threading.Timer(10, self.__watch_and_store_partitions).start()
python类Timer()的实例源码
def Update(self):
# Get our wake-up thread ready...
self.ticker = threading.Timer(self.INTERVAL, self.Update)
try:
# Check if any of our topics have new info to pass on
if len(self.topics):
refresh = False
for topic in self.topics.itervalues():
topic.Update(self)
if topic.HasChanged():
refresh = True
topic.Reset()
if refresh:
self.SignalExcel()
finally:
self.ticker.start() # Make sure we get to run again
def doRpcServer(port, stopTimeSec):
class EchoHandler(object):
def Echo123(self, msg1, msg2, msg3):
return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3))
def EchoStruct(self, msg):
return ("%s" % msg)
addr = msgpackrpc.Address('localhost', port)
server = msgpackrpc.Server(EchoHandler())
server.listen(addr)
# run thread to stop it after stopTimeSec seconds if > 0
if stopTimeSec > 0:
def myStopRpcServer():
server.stop()
t = threading.Timer(stopTimeSec, myStopRpcServer)
t.start()
server.start()
def doRpcServer(port, stopTimeSec):
class EchoHandler(object):
def Echo123(self, msg1, msg2, msg3):
return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3))
def EchoStruct(self, msg):
return ("%s" % msg)
addr = msgpackrpc.Address('localhost', port)
server = msgpackrpc.Server(EchoHandler())
server.listen(addr)
# run thread to stop it after stopTimeSec seconds if > 0
if stopTimeSec > 0:
def myStopRpcServer():
server.stop()
t = threading.Timer(stopTimeSec, myStopRpcServer)
t.start()
server.start()
def __init__(self, host='192.168.1.1'):
self.host = host
self.sequence = 1
self.timer = 0.2
self.com_watchdog_timer = threading.Timer(self.timer, self.commwdg)
self.lock = threading.Lock()
self.speed = 0.2
self.at(ardrone.at.config, 'general:navdata_demo', 'TRUE')
self.at(ardrone.at.config, 'control:altitude_max', '20000')
self.video_pipe, video_pipe_other = multiprocessing.Pipe()
self.nav_pipe, nav_pipe_other = multiprocessing.Pipe()
self.com_pipe, com_pipe_other = multiprocessing.Pipe()
self.network_process = ardrone.network.ARDroneNetworkProcess(self.host, nav_pipe_other, video_pipe_other, com_pipe_other)
self.network_process.start()
self.ipc_thread = ardrone.network.IPCThread(self)
self.ipc_thread.start()
self.image = PIL.Image.new('RGB', (640, 360))
self.navdata = dict()
self.time = 0
def keep_status_bar_cover_alive(dev):
"""
keep sending 'turn on status bar cover' broadcast, for the cover effect is not very perfect
:param dev: device id to process
:return: None
"""
StatusBarCover.switch_cover(dev, True)
threading.Timer(5, keep_status_bar_cover_alive, [dev]).start()
def adjust_limits(self):
self.logger.info("adjust_limits: checking midpoint limits")
current_time = datetime.datetime.today()
for orderid in self.openorders.keys():
if self.openorders[orderid].adjust_periodical == True and orderid in self.__MapToExecuteOrderID:
if (current_time - self.openorders[orderid].last_adjust).total_seconds() > self.limit_adjust_interval*0.9:
contract = self.openorders[orderid].contract
if (current_time - self.openorders[orderid].placed_date) >= self.max_adjust_time:
self.openorders[orderid].ba_offset = 0
self.logger.info("adjust_limits: %s setting ba_offset to zero because max_adjust_time as passed",self.openorders[orderid].contract.m_symbol)
midpoint = self._calc_midpoint(self.openorders[orderid].bid,self.openorders[orderid].ask,self.openorders[orderid].ba_offset,self.openorders[orderid].action,oderid=orderid)
self.logger.debug("midpoint %s", midpoint)
if midpoint is not None:
order = makeStkOrder(self.openorders[orderid].vollume, self.openorders[orderid].action, self._account, ordertype=self.openorders[orderid].ordertype)
order.m_lmtPrice = midpoint
exec_orderid = self.__MapToExecuteOrderID[orderid]
self.con.placeOrder(exec_orderid,contract,order)
self.openorders[orderid].last_adjust = datetime.datetime.today()
self.openorders[orderid].limitprice = order.m_lmtPrice
self.logger.info("adjust_limits: Updated %s order with id %s to %s (bid: %s / ask: %s)",self.openorders[orderid].contract.m_symbol, orderid, order.m_lmtPrice, self.openorders[orderid].bid, self.openorders[orderid].ask)
#reschedule the timer
if len(self.openorders.keys()) > 0:
self.adjist_limits_thread = Timer(self.limit_adjust_interval, self.adjust_limits, ()).start()
else:
self.adjist_limits_thread = None
def buildrunning():
if keepalive:
threading.Timer(10.0, buildrunning).start()
if not error:
checkJobsBuilding()
# Initiate the threads
def repeat(self):
try:
self.udpHeartbeat()
except Exception as e:
self.logger.exception(e)
except:
self.logger.error("error on executing heartbeat: {0} ".format(sys.exc_info()[0]))
timer = threading.Timer(self.udpHeartbeatSeconds, self.repeat)
timer.daemon = True
timer.start()
def start(self):
self.loadState()
self.serverHandler.start()
sslThread = threading.Thread(target = self.startSsl)
sslThread.daemon = True
sslThread.start()
timer = threading.Timer(self.taskIntervalSecond, self.repeat)
timer.daemon = True
timer.start()
self.udpServer = SocketServer.UDPServer((self.udpHost, self.udpPort), IotUDPHandler)
self.logger.info("starting UDP server listening at {0}:{1}".format(self.udpServer.server_address[0], self.udpServer.server_address[1]))
self.udpServer.service = self
self.udpServer.role = IotUDPHandler.SERVER
self.udpServer.serve_forever()
def repeat(self):
try:
self.task()
except Exception as e:
self.logger.exception(e)
except:
self.logger.error("error on executing task: {0} ".format(sys.exc_info()[0]))
timer = threading.Timer(self.taskIntervalSecond, self.repeat)
timer.daemon = True
timer.start()
def start(self):
self.logger.info("starting device handler")
threading.Timer(7, self.test).start()
def on_deactivated(self, view):
# TODO Review clearing the cmdline history, does it need to be an event?
# Because views load asynchronously, do not restore history index
# .on_activated(), but here instead. Otherwise, the .score_selector()
# call won't yield the desired results.
if view.score_selector(0, 'text.excmdline') > 0:
view.run_command('clear_cmdline_history_index')
self._on_deactivate_callback_timer = Timer(0.25, self._on_deactivate_callback)
self._on_deactivate_callback_timer.start()
def start(self):
"""Start periodically sending registration messages after threshold amount of time"""
if not self.send_messages:
self.send_messages = True
self.current_thread = threading.Timer(self.threshold, self._wake)
self.current_thread.start()
def _wake(self):
"""This class periodically sends registration messages using Clog"""
if self.send_messages:
self.publish_registration_messages()
# The purpose of the Timer is for _wake to ensure it is called
self.current_thread = threading.Timer(self.threshold, self._wake)
self.current_thread.start()
def _update_database(self):
"""
Determines if a database update is needed and if so downloads a new one from MaxMind
"""
if not self._download_database:
logger.warning("_update_database called while in pre-specified database"
" mode... returning without updates...")
return
logger.info("Checking for MaxMind database updates...")
try:
if not self._is_update_needed():
logger.info("No database updates to retrieve.")
return
logger.info("Retrieving MaxMind Database...")
response = requests.get(self.MAXMIND_FREE_DB_URL)
response.raise_for_status()
logger.info('Retrieved MaxMind database.')
data = gzip.GzipFile(fileobj=StringIO.StringIO(response.content))
# Write the database to a temporary file
fd, file_path = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as temp_file:
temp_file.write(data.read())
self._swap_database(file_path)
logger.info("MaxMind database updated.")
except:
logger.exception("Failed to update MaxMind database.")
finally:
# Schedule this function to run again in the configured update interval
self._update_thread = Timer(self._update_interval * 60 * 60, self._update_database)
self._update_thread.daemon = True
self._update_thread.start()
def run(self):
while self.__running.isSet():
self.__flag.wait()
while not self.thread_stop:
'?????????,?????????'
try:
if self.queue.empty() is False:
__task = self.queue.get() # ????
assert isinstance(__task, dict)
if __task['func'] != None:
eval(__task['func'])
self.queue.__task_done() # ??????
else:
pass
else:
QA_util_log_info("From Engine %s Engine will waiting for new task ..." % str(
threading.current_thread()))
time.sleep(1)
except:
time.sleep(1)
self.run()
__res = self.__QA_queue_status() # ????????
if __res > 0:
#QA_util_log_info("From Engine %s: There are still %d tasks to do" % (str(threading.current_thread()), __res))
pass
# input()
threading.Timer(0.005, self.run)
def __init__(self, *args, **kwds):
self.logger = logging.getLogger(str(self.__class__.__name__))
self.__class__.Timers.append(self)
self.timer = threading.Timer(*args, **kwds)
def __getattr__(self, name):
try:
return super(Timer, self).__getattr(name)
except AttributeError as e:
if self.timer:
return getattr(self.timer, name)
else:
raise