本文整理汇总了Python中twisted.internet.reactor.seconds函数的典型用法代码示例。如果您正苦于以下问题:Python seconds函数的具体用法?Python seconds怎么用?Python seconds使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了seconds函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_position_update
def on_position_update(self):
if self.protocol.running_man:
if self.link is not None and self.link.hp > 0:
dist = distance_3d_vector(self.world_object.position,
self.link.world_object.position)
if dist > LINK_DISTANCE:
self.grenade_suicide()
self.link_deaths += 1
self.link.grenade_suicide()
self.link.link_deaths += 1
message = S_LINK_BREAK.format(player = self.link.name)
self.send_chat(message)
message = S_LINK_BREAK.format(player = self.name)
self.link.send_chat(message)
elif (dist > LINK_WARNING_DISTANCE and
(self.last_warning is None or
seconds() - self.last_warning > 2.0)):
self.last_warning = seconds()
self.link.last_warning = seconds()
message = S_LINK_WARNING.format(player = self.link.name)
self.send_chat(message)
message = S_LINK_WARNING.format(player = self.name)
self.link.send_chat(message)
connection.on_position_update(self)
示例2: on_team_join
def on_team_join(self, team):
if self.team is not None:
if self.protocol.teamswitch_interval:
teamswitch_interval = self.protocol.teamswitch_interval
if teamswitch_interval == 'never':
self.send_chat('Switching teams is not allowed')
return False
if (self.last_switch is not None and
reactor.seconds() - self.last_switch < teamswitch_interval * 60):
self.send_chat('You must wait before switching teams again')
return False
if team.locked:
self.send_chat('Team is locked')
if not team.spectator and not team.other.locked:
return team.other
return False
balanced_teams = self.protocol.balanced_teams
if balanced_teams and not team.spectator:
other_team = team.other
if other_team.count() < team.count() + 1 - balanced_teams:
if other_team.locked:
return False
self.send_chat('Team is full, moved to %s' % other_team.name)
return other_team
self.last_switch = reactor.seconds()
示例3: use_ability
def use_ability(self, mode):
ability = ABILITIES[mode]
if 'cooldown' in ability:
min_cd = ability['cooldown']
last_used = 0
if mode in self.ability_cooldown:
last_used = self.ability_cooldown[mode]
current_cd = reactor.seconds() - last_used
if current_cd < min_cd - self.cooldown_margin:
self.cooldown_strikes += 1
if self.cooldown_strikes > self.max_cooldown_strikes:
self.log(("ability used before cooldown was ready. " +
"mode={mode}, min. cooldown={mincd}s, " +
"current cooldown={currentcd}s")
.format(mode=mode,
mincd=min_cd,
currentcd=current_cd),
LOG_LEVEL_VERBOSE)
return False
else:
self.cooldown_strikes = 0
# keep track of ability usage
self.ability_cooldown[mode] = reactor.seconds()
return True
示例4: on_chat
def on_chat(self, message):
if self.time_last_chat < int(reactor.seconds() - constants.ANTISPAM_LIMIT_CHAT):
self.chat_messages_burst = 0
else:
if self.chat_messages_burst < constants.ANTISPAM_BURST_CHAT:
self.chat_messages_burst += 1
else:
self.time_last_chat = reactor.seconds()
res = self.scripts.call('on_spamming_chat').result
if not res:
# As we do not want to spam back only do this when
# burst limit is reached for the first time
if self.chat_messages_burst == constants.ANTISPAM_BURST_CHAT:
if self.server.config.base.auto_kick_spam:
self.kick('Kicked for chat spamming')
else:
self.send_chat('[ANTISPAM] Please do not spam in chat!')
return
if message.startswith('/'):
command, args = parse_command(message[1:])
self.on_command(command, args)
return
event = self.scripts.call('on_chat', message=message)
if event.result is False:
return
return event.message
示例5: with_lock
def with_lock(reactor, lock, func, log=None, acquire_timeout=None, release_timeout=None):
"""
Context manager for any lock object that contains acquire() and release() methods
"""
if log:
log.msg('Starting lock acquisition')
d = defer.maybeDeferred(lock.acquire)
if acquire_timeout is not None:
timeout_deferred(d, acquire_timeout, reactor, 'Lock acquisition')
if log:
d.addCallback(log_with_time, reactor, log, reactor.seconds(),
'Lock acquisition', 'acquire_time')
d.addErrback(log_with_time, reactor, log, reactor.seconds(),
'Lock acquisition failed')
def release_lock(result):
if log:
log.msg('Starting lock release')
d = defer.maybeDeferred(lock.release)
if release_timeout is not None:
timeout_deferred(d, release_timeout, reactor, 'Lock release')
if log:
d.addCallback(
log_with_time, reactor, log, reactor.seconds(), 'Lock release', 'release_time')
return d.addCallback(lambda _: result)
def lock_acquired(_):
d = defer.maybeDeferred(func).addBoth(release_lock)
return d
d.addCallback(lock_acquired)
return d
示例6: getChild
def getChild(self, path, request):
pre_check=[False, False]
host, port = self.__get_host_info(request)
if self.domain_level ==0 :
ts = reactor.seconds()
if self.domains_blocked_cache.has_key(host) and ( ts - self.domains_blocked_cache[host][0] ) <= 10 :
print self.domains_blocked_cache[host][1]
block_d = BlockingDeferred(self.domains_blocked_cache[host][1])
try:
pre_check, categories = block_d.blockOn()
print "Host %s , verified [cached] (pre_check=%s)" % (host, pre_check)
except:
print "Something wrong validating domain %s" % host
pre_check = [False, False]
else:
query = self.filter_manager.check_domain_defer(self.uid, host)
self.domains_blocked_cache[host]=[reactor.seconds(), query]
block_d = BlockingDeferred(query)
try:
pre_check, categories = block_d.blockOn()
print "Host %s , verified (pre_check=%s)" % (host, pre_check)
except:
print "Something wrong validating domain %s" % host
pre_check = [False, False]
return ReverseProxyResource(self.uid, self.filter_manager, reactor=reactor,
domain_level=self.domain_level + 1,
pre_check=pre_check)
else:
return ReverseProxyResource(self.uid, self.filter_manager, reactor=reactor,
domain_level=self.domain_level + 1,
pre_check=self.pre_check)
示例7: html_grief_check
def html_grief_check(ignore, player, time):
color = False
minutes = float(time or 2)
if minutes < 0.0:
raise ValueError()
time = reactor.seconds() - minutes * 60.0
blocks_removed = player.blocks_removed or []
blocks = [b[1] for b in blocks_removed if b[0] >= time]
player_name = player.name
if color:
player_name = (('\x0303' if player.team.id else '\x0302') +
player_name + '\x0f')
message = '%s removed %s block%s in the last ' % (player_name,
len(blocks) or 'no', '' if len(blocks) == 1 else 's')
if minutes == 1.0:
minutes_s = 'minute'
else:
minutes_s = '%s minutes' % ('%f' % minutes).rstrip('0').rstrip('.')
message += minutes_s + '.'
if len(blocks):
infos = set(blocks)
infos.discard(None)
if color:
names = [('\x0303' if team else '\x0302') + name for name, team in
infos]
else:
names = set([name for name, team in infos])
if len(names) > 0:
message += (' Some of them were placed by ' +
('\x0f, ' if color else ', ').join(names))
message += '\x0f.' if color else '.'
else:
message += ' All of them were map blocks.'
last = blocks_removed[-1]
time_s = prettify_timespan(reactor.seconds() - last[0], get_seconds = True)
message += ' Last one was destroyed %s ago' % time_s
whom = last[1]
if whom is None and len(names) > 0:
message += ', and was part of the map'
elif whom is not None:
name, team = whom
if color:
name = ('\x0303' if team else '\x0302') + name + '\x0f'
message += ', and belonged to %s' % name
message += '.'
switch_sentence = False
if player.last_switch is not None and player.last_switch >= time:
time_s = prettify_timespan(reactor.seconds() - player.last_switch,
get_seconds = True)
message += ' %s joined %s team %s ago' % (player_name,
player.team.name, time_s)
switch_sentence = True
teamkills = len([t for t in player.teamkill_times or [] if t >= time])
if teamkills > 0:
s = ', and killed' if switch_sentence else ' %s killed' % player_name
message += s + ' %s teammates in the last %s' % (teamkills, minutes_s)
if switch_sentence or teamkills > 0:
message += '.'
return message
示例8: on_position_update
def on_position_update(self):
# send jump action tip when you're near one
if self.protocol.machineguns and not self.machinegun and self.hp > 0:
last_message = self.last_machinegun_message
available = last_message is None or seconds() - last_message > 10.0
if (available and any(mg.actionable(self) for mg in
self.protocol.machineguns)):
self.send_chat(S_JUMP_TO_USE)
self.last_machinegun_message = seconds()
connection.on_position_update(self)
示例9: test_timeout
def test_timeout(self):
from time import sleep
t0 = reactor.seconds()
try:
rsp = yield self.getPage("http://127.0.0.1:%d/" % self._port,
timeout=self.requestTimeout)
except netErr.TimeoutError:
self.assertEquals(self.requestTimeout, int(reactor.seconds()-t0))
else:
fail("Did not timeout")
示例10: update_world
def update_world(self):
last_time = self.last_time
current_time = reactor.seconds()
if last_time is not None:
dt = current_time - last_time
if dt > 1.0:
print '(warning: high CPU usage detected - %s)' % dt
self.last_time = current_time
ServerProtocol.update_world(self)
time_taken = reactor.seconds() - current_time
if time_taken > 1.0:
print 'World update iteration took %s, objects: %s' % (time_taken,
self.world.objects)
示例11: pollDatabaseBuildRequests
def pollDatabaseBuildRequests(self):
# deal with cleaning up unclaimed requests, and (if necessary)
# requests from a previous instance of this master
timer = metrics.Timer("BuildMaster.pollDatabaseBuildRequests()")
timer.start()
# cleanup unclaimed builds
since_last_cleanup = reactor.seconds() - self._last_claim_cleanup
if since_last_cleanup < self.RECLAIM_BUILD_INTERVAL:
unclaimed_age = (self.RECLAIM_BUILD_INTERVAL
* self.UNCLAIMED_BUILD_FACTOR)
wfd = defer.waitForDeferred(
self.db.buildrequests.unclaimExpiredRequests(unclaimed_age))
yield wfd
wfd.getResult()
self._last_claim_cleanup = reactor.seconds()
# _last_unclaimed_brids_set tracks the state of unclaimed build
# requests; whenever it sees a build request which was not claimed on
# the last poll, it notifies the subscribers. It only tracks that
# state within the master instance, though; on startup, it notifies for
# all unclaimed requests in the database.
last_unclaimed = self._last_unclaimed_brids_set or set()
if len(last_unclaimed) > self.WARNING_UNCLAIMED_COUNT:
log.msg("WARNING: %d unclaimed buildrequests - is a scheduler "
"producing builds for which no builder is running?"
% len(last_unclaimed))
# get the current set of unclaimed buildrequests
wfd = defer.waitForDeferred(
self.db.buildrequests.getBuildRequests(claimed=False))
yield wfd
now_unclaimed_brdicts = wfd.getResult()
now_unclaimed = set([ brd['brid'] for brd in now_unclaimed_brdicts ])
# and store that for next time
self._last_unclaimed_brids_set = now_unclaimed
# see what's new, and notify if anything is
new_unclaimed = now_unclaimed - last_unclaimed
if new_unclaimed:
brdicts = dict((brd['brid'], brd) for brd in now_unclaimed_brdicts)
for brid in new_unclaimed:
brd = brdicts[brid]
self.buildRequestAdded(brd['buildsetid'], brd['brid'],
brd['buildername'])
timer.stop()
示例12: on_shoot_set
def on_shoot_set(self, fire):
self.fire = fire
if self.tool == WEAPON_TOOL:
self.weap1 = self.weapon_object.name
if self.fire and seconds() - self.start_set_time >= 1 and seconds() - self.end_set_time >= 1:
self.start_ammo = self.weapon_object.current_ammo
self.orient_count = 0
self.junction = True
self.start_set_time = seconds()
elif not self.fire and self.junction and seconds() - self.start_set_time >= .05 and self.world_object.orientation.z >= -0.95 and self.world_object.orientation.z <= 0.95:
self.end_set_time = seconds()
callLater(0.05, self.recoiltest)
elif not self.fire and self.start_ammo != self.weapon_object.current_ammo:
self.junction = False
return connection.on_shoot_set(self, fire)
示例13: data_received
def data_received(self, peer, packet):
ip = peer.address.host
current_time = reactor.seconds()
try:
ServerProtocol.data_received(self, peer, packet)
except (NoDataLeft, InvalidData):
import traceback
traceback.print_exc()
print 'IP %s was hardbanned for invalid data or possibly DDoS.' % ip
self.hard_bans.add(ip)
return
dt = reactor.seconds() - current_time
if dt > 1.0:
print '(warning: processing %r from %s took %s)' % (
packet.data, ip, dt)
示例14: with_lock
def with_lock(reactor, lock, func, log=default_log, acquire_timeout=None,
release_timeout=None, held_too_long=120):
"""
Context manager for any lock object that contains acquire() and release()
methods
"""
held = [True]
log = log.bind(lock_status="Acquiring",
lock=lock,
locked_func=func)
log.msg('Starting lock acquisition')
d = defer.maybeDeferred(lock.acquire)
if acquire_timeout is not None:
timeout_deferred(d, acquire_timeout, reactor, 'Lock acquisition')
d.addCallback(log_with_time, reactor, log.bind(lock_status='Acquired'),
reactor.seconds(), 'Lock acquisition', 'acquire_time')
d.addErrback(log_with_time, reactor, log.bind(lock_status='Failed'),
reactor.seconds(), 'Lock acquisition failed')
def release_lock(result, log):
log.msg('Starting lock release', lock_status="Releasing")
d = defer.maybeDeferred(lock.release)
if release_timeout is not None:
timeout_deferred(d, release_timeout, reactor, 'Lock release')
d.addCallback(
log_with_time, reactor, log.bind(lock_status="Released"),
reactor.seconds(),
'Lock release', 'release_time')
def finished_release(_):
held[0] = False
return result
return d.addCallback(finished_release)
def check_still_acquired(log):
if held[0]:
log.msg("Lock held for more than %s seconds!" % (held_too_long,),
isError=True)
def lock_acquired(acquire_result, log):
log = log.bind(lock_status="Acquired")
reactor.callLater(held_too_long, check_still_acquired, log)
d = defer.maybeDeferred(func).addBoth(release_lock, log)
return d
d.addCallback(lock_acquired, log)
return d
示例15: buildFinished
def buildFinished(self, build, sb):
"""This is called when the Build has finished (either success or
failure). Any exceptions during the build are reported with
results=FAILURE, not with an errback."""
# by the time we get here, the Build has already released the slave,
# which will trigger a check for any now-possible build requests
# (maybeStartBuilds)
results = build.build_status.getResults()
self.building.remove(build)
if results == RETRY:
d = self._resubmit_buildreqs(build)
d.addErrback(log.err, 'while resubmitting a build request')
else:
complete_at_epoch = reactor.seconds()
complete_at = epoch2datetime(complete_at_epoch)
brids = [br.id for br in build.requests]
d = self.master.data.updates.completeBuildRequests(brids, results, complete_at=complete_at)
# nothing in particular to do with this deferred, so just log it if
# it fails..
d.addErrback(log.err, 'while marking build requests as completed')
if sb.slave:
sb.slave.releaseLocks()
self.updateBigStatus()