本文整理汇总了Python中threading.Timer.setDaemon方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.setDaemon方法的具体用法?Python Timer.setDaemon怎么用?Python Timer.setDaemon使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Timer
的用法示例。
在下文中一共展示了Timer.setDaemon方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: activate
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def activate(self, conf, glob):
protocols.activate(self, conf, glob)
self.request = Queue()
self.response = Queue()
self.p = Process(target=root, args=(self.request, self.response))
self.p.start()
self.valuestore = ConfigParser()
self.valuestore.add_section('values')
self.valuesfile = path.join(path.dirname(__file__), 'values.conf')
for item in itemList:
self.valuestore.set('values', item['name'], item['value'])
self.valuestore.read(self.valuesfile)
f = open(self.valuesfile, 'w')
self.valuestore.write(f)
f.close()
try:
uid = pwd.getpwnam(self.glob['conf'].USER).pw_uid
gid = grp.getgrnam(self.glob['conf'].GROUP).gr_gid
os.chown(self.valuesfile, uid, gid)
except:
pass
t = Timer(5, self.calc_thread)
t.setDaemon(True)
t.start()
示例2: RepeatedTimer
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.setDaemon(True)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
示例3: ChatRoom
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
class ChatRoom(BotPlugin):
connected = False
def keep_alive(self):
logging.debug('Keep alive sent')
self.send('nobody', ' ', message_type='groupchat') # hack from hipchat itself
self.t = Timer(60.0, self.keep_alive)
self.t.setDaemon(True) # so it is not locking on exit
self.t.start()
def callback_connect(self):
logging.info('Callback_connect')
if not self.connected:
self.connected = True
for room in CHATROOM_PRESENCE:
logging.info('Join room ' + room)
self.join_room(room, CHATROOM_FN)
logging.info('Start kepp alive')
self.keep_alive()
def callback_message(self, conn, mess):
#if mess.getBody():
# logging.debug(u'Received message %s' % mess.getBody())
if mess.getType() in ('groupchat', 'chat'):
try:
username = get_jid_from_message(mess)
if username in CHATROOM_RELAY:
logging.debug('Message to relay from %s.' % username)
body = mess.getBody()
rooms = CHATROOM_RELAY[username]
for room in rooms:
self.send(room, body, message_type='groupchat')
except Exception, e:
logging.exception('crashed in callback_message %s' % e)
示例4: program_next_poll
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def program_next_poll(self, interval, method, args, kwargs):
t = Timer(interval=interval, function=self.poller,
kwargs={'interval': interval, 'method': method, 'args': args, 'kwargs': kwargs})
self.current_timers.append(t) # save the timer to be able to kill it
t.setName('Poller thread for %s' % type(method.__self__).__name__)
t.setDaemon(True) # so it is not locking on exit
t.start()
示例5: RESTAnovaController
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
class RESTAnovaController(AnovaController):
"""
This version of the Anova Controller will keep a connection open over bluetooth
until the timeout has been reach.
NOTE: Only a single BlueTooth connection can be open to the Anova at a time.
"""
TIMEOUT = 5 * 60 # Keep the connection open for this many seconds.
TIMEOUT_HEARTBEAT = 20
def __init__(self, mac_address, connect=True, logger=None):
self.last_command_at = datetime.datetime.now()
if logger:
self.logger = logger
else:
self.logger = logging.getLogger()
super(RESTAnovaController, self).__init__(mac_address, connect=connect)
def set_timeout(self, timeout):
"""
Adjust the timeout period (in seconds).
"""
self.TIMEOUT = timeout
def timeout(self, seconds=None):
"""
Determines whether the Bluetooth connection should be timed out
based on the timestamp of the last exectuted command.
"""
if not seconds:
seconds = self.TIMEOUT
timeout_at = self.last_command_at + datetime.timedelta(seconds=seconds)
if datetime.datetime.now() > timeout_at:
self.close()
self.logger.info('Timeout bluetooth connection. Last command ran at {0}'.format(self.last_command_at))
else:
self._timeout_timer = Timer(self.TIMEOUT_HEARTBEAT, lambda: self.timeout())
self._timeout_timer.setDaemon(True)
self._timeout_timer.start()
self.logger.debug('Start connection timeout monitor. Will idle timeout in {0} seconds.'.format(
(timeout_at - datetime.datetime.now()).total_seconds()))
def connect(self):
super(RESTAnovaController, self).connect()
self.last_command_at = datetime.datetime.now()
self.timeout()
def close(self):
super(RESTAnovaController, self).close()
try:
self._timeout_timer.cancel()
except AttributeError:
pass
def _send_command(self, command):
if not self.is_connected:
self.connect()
self.last_command_at = datetime.datetime.now()
return super(RESTAnovaController, self)._send_command(command)
示例6: __init__
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
class UpdatedURL:
def __init__(self, url):
self.url = url
self.contents = ''
self.last_updated = None
self.update()
def update(self):
self.contents = urlopen(self.url).read()
self.last_updated = datetime.datetime.now()
self.schedule()
def schedule(self):
self.timer = Timer(3600, self.update)
self.timer.setDaemon(True)
self.timer.start()
def __getstate__(self):
new_state = self.__dict__.copy()
if 'timer' in new_state:
del new_state['timer']
return new_state
def __setstate__(self, data):
self.__dict__ = data
self.schedule()
开发者ID:Dennitizer,项目名称:Python_Master-the-Art-of-Design-Patterns,代码行数:28,代码来源:1261_10_25_state_pickling.py
示例7: start_timer_delete
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def start_timer_delete():
""" Metoda za pokretanje tajmera koji ce pozvati metodu za brisanje instanci """
delete_time = random.gauss(delete_interval, deviation)
timer = Timer(delete_time, delete_instances)
timer.setDaemon(True)
timer.start()
print('Scheduled delete timer task %d sec' % (delete_time))
示例8: ddns_update
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def ddns_update():
h = httplib2.Http()
my_addr_host = "http://ipecho.net/plain"
try:
resp, external_ip = h.request(my_addr_host)
except:
print("failed to get address from [" + my_addr_host + "]")
try:
my_addr_host = "http://myexternalip.com/raw" # IPv6
resp, external_ip = h.request(my_addr_host)
except:
print("failed to get address from [" + my_addr_host + "]")
ddns_timer = Timer(ddns_update_interval_sec, ddns_update)
ddns_timer.setDaemon(True)
ddns_timer.start()
return
print("My IP address is [" + str(external_ip).strip() + "]")
#h.add_credentials(ddns_username, ddns_password)
update_dynu_ddns_url = "https://api.dynu.com/nic/update?hostname=" + ddns_hostname + "&username=" + ddns_username + "&myip=" + str(external_ip).strip() + "&password=" + ddns_password
#update_noip_dns_url = "http://dynupdate.no-ip.com/nic/update?hostname=" + ddns_hostname + "&myip=" + external_ip.strip() + ""
print("Update DYNU url [" + update_dynu_ddns_url + "]")
resp = requests.get(update_dynu_ddns_url)
print("DDNS response [" + str(resp.content) + "]")
ddns_timer = Timer(ddns_update_interval_sec, ddns_update)
ddns_timer.setDaemon(True)
ddns_timer.start()
示例9: start_timer_start
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def start_timer_start():
""" Metoda za pokretanje tajmera koji ce pozvati metodu za pokretanje instanci """
start_time = random.gauss(start_interval, deviation)
timer = Timer(start_time, start_instances)
timer.setDaemon(True)
timer.start()
print('Scheduled start timer task %d sec' % (start_time))
示例10: timer_thread
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def timer_thread(timeout_arg):
for neighbor in deepcopy(neighbors):
if neighbor in timer_log:
t_threshold = (3 * timeout_arg)
if ((int(time.time()) - timer_log[neighbor]) > t_threshold):
if routing_table[neighbor]['cost'] == INFINITY:
broadcast_routing_table()
else:
routing_table[neighbor]['cost'] = INFINITY
routing_table[neighbor]['link'] = "NULL"
del neighbors[neighbor]
for node in routing_table:
if node in neighbors:
routing_table[node]['cost'] = adjacent_links[node]
routing_table[node]['link'] = node
else:
routing_table[node]['cost'] = INFINITY
routing_table[node]['link'] = "NULL"
send_dict = { 'source': 'close', 'target': neighbor }
for neighbor in neighbors:
temp = neighbor.split(':')
recvSock.sendto(json.dumps(send_dict), (temp[0], int(temp[1])))
timer = Timer(3, timer_thread, [timeout_arg])
timer.setDaemon(True)
timer.start()
示例11: certificate_renewal
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def certificate_renewal():
# get next renewal time from config file
# if the renewal time has come, renew the certificate
os.system("sudo python2.7 certificate_renewal.py")
certificate_renewal_timer = Timer(certificate_renewal_interval, certificate_renewal)
certificate_renewal_timer.setDaemon(True)
certificate_renewal_timer.start()
示例12: _upload_file
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def _upload_file(filename):
"""
Upload the file `filename` to the configured sharing service, and shortens
the URL with the configured URL shortener. Also copies the shortened URL
to the clipboard, and runs the post upload hook (if there is one).
"""
configmanager = get_conf_manager()
sharingservice = get_sharing_service_from_conf(configmanager)
urlprovider = get_url_shortener_from_conf(configmanager)
try:
StatusIcon().statusicon.set_icon_from_file(os.path.join(PATHS['ICONS_PATH'], 'icon-uploading.png'))
# Store the file online
url = sharingservice.store(filename)
print 'Saved to', url
except Exception, e:
import traceback
traceback.print_exc()
print type(e)
if isinstance(e, SharingError):
try:
title = e.args[1]
except IndexError:
title = e.default_title
notify(title, e.args[0])
elif isinstance(e, URLError):
notify('Connection error', 'You may be disconnected from the internet, or the server you are using may be down.')
StatusIcon().statusicon.set_icon_from_file(os.path.join(PATHS['ICONS_PATH'], 'icon-uploadfailed.png'))
timer = Timer(5, StatusIcon().reset_icon)
timer.setDaemon(True)
timer.start()
return None
示例13: _func
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def _func():
open_view(im)
if auto_close:
minutes = 2
t = Timer(60 * minutes, im.close_ui)
t.setDaemon(True)
t.start()
示例14: wrapper
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
def wrapper(*args, **kwargs):
semaphore.acquire()
result = fn(*args, **kwargs)
timer = Timer(every, semaphore.release)
timer.setDaemon(True)
timer.start()
return result
示例15: NotifyingPropertyReader
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import setDaemon [as 别名]
class NotifyingPropertyReader(SimplePropertyReader):
def __init__(self, _file, _separator, startAsDaemon = False):
super(NotifyingPropertyReader, self).__init__(_file, _separator)
self.listeners = []
self.startAsDaemon = startAsDaemon
self.lastModifiedDate = os.path.getmtime(self.file)
self.startWatcher()
def startWatcher(self):
self.timer = Timer(1, self.determineIfPropertyHasChanged)
self.timer.setDaemon(self.startAsDaemon)
self.timer.start()
def addListener(self, propertyChangedListener):
self.listeners.append(propertyChangedListener)
def removeListener(self, propertyChangedListener):
self.listeners.remove(propertyChangedListener)
def notifyListeners(self):
print "notifying listeners"
map(lambda x : x(self.properties), self.listeners)
def determineIfPropertyHasChanged(self):
print "timer has fired"
if self.lastModifiedDate != os.path.getmtime(self.file):
self.readProperties()
self.notifyListeners()
self.lastModifiedDate = os.path.getmtime(self.file)
self.startWatcher()