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 # gremlin.util.log("init") # for n,arg in enumerate(args): # gremlin.util.log("arg: {}: {}".format(n,arg)) # for n,arg in kwargs.items(): # gremlin.util.log("kwarg: {}: {}".format(n,arg)) self.start() def _run(self): self.is_running = False gremlin.util.log("run 1") self.function(*self.args, **self.kwargs) gremlin.util.log("run 2") self.start() def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self._timer.join() self.is_running = False gremlin.util.log("stop")
def backup_loop(self): msg_timer = Timer(1.0, self.become_master) self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.bind((self.IP, self.PORT)) msg_timer.start() print("This is backup speaking") while True: if (self.socket.recv != None): data = int.from_bytes(self.socket.recv(10), byteorder='big') print("bu:", data) self.current_number = data msg_timer.cancel() msg_timer.join() msg_timer = Timer(1.0, self.become_master) msg_timer.start() if (not msg_timer.is_alive()): msg_timer.join() break
class TimedClose: def __init__(self, app: 'WebApp', timeout=TIMEOUT): self._timeout = timeout self._app = app self._timer = None def activateTimer(self): if self._timer is None: self._startTimer() else: if self._timer.is_alive(): # cancel and reschedule self.closeTimer() # new timer self._startTimer() def _startTimer(self): self._timer = Timer(self._timeout, self._timerFinished) self._timer.setDaemon(True) self._timer.start() def closeTimer(self): if self._timer is not None: self._timer.cancel() self._timer.join() self._timer = None def _timerFinished(self): # just showing the main screen self._timer = None self._app.showPrevFSBox()
def test_sqs_longpoll(self): c = SQSConnection() queue_name = "test_sqs_longpoll_%s" % int(time.time()) queue = c.create_queue(queue_name) self.addCleanup(c.delete_queue, queue, True) messages = [] # The basic idea is to spawn a timer thread that will put something # on the queue in 5 seconds and verify that our long polling client # sees the message after waiting for approximately that long. def send_message(): messages.append(queue.write(queue.new_message("this is a test message"))) t = Timer(5.0, send_message) t.start() self.addCleanup(t.join) start = time.time() response = queue.read(wait_time_seconds=10) end = time.time() t.join() self.assertEqual(response.id, messages[0].id) self.assertEqual(response.get_body(), messages[0].get_body()) # The timer thread should send the message in 5 seconds, so # we're giving +- .5 seconds for the total time the queue # was blocked on the read call. self.assertTrue(4.5 <= (end - start) <= 5.5)
class UbuntuNotify: ''' This package is ment to help impliment custom notifications in Linux. The package has been tested in Ubuntu 20.04 ''' __NotificationSent = [] def __init__(self): """ Make sure the platform is Linux and start the main thread """ if platform != "linux": raise Exception("This package is ment for Linux!") self.gmail = GmailApi() self.startProcess() def startProcess(self): """ Start the background process that receives the email data """ self.thread = Timer(60, self.startProcess) self.thread.start() newEmail = self.gmail.getLatestEmail() # Make sure the email dict is not empty if newEmail != {}: # Make sure the email notification was only sent once if newEmail['subject'] not in self.__NotificationSent: self.__NotificationSent.append(newEmail['subject']) Notification(newEmail) self.thread.join()
def run(self): while not self.stopThread: t = Timer(5, self.kill) t.start() t.join()
class Timeout(object): """Utility class for adding a timeout to an event. :param time_or_event: A number, in seconds, or a threading.Event object. :ivar event: The Event associated with the Timeout. :ivar timer: The Timer associated with the Timeout, if any. """ def __init__(self, time_or_event): if isinstance(time_or_event, Number): self.event = Event() self.timer = Timer(time_or_event, self.event.set) else: self.event = time_or_event self.timer = None def __enter__(self): if self.timer: self.timer.start() return self.event def __exit__(self, exc_type, exc_val, exc_tb): if self.timer: self.timer.cancel() self.timer.join()
class Block(Play): def __init__(self, owner, cardType): super(Block, self).__init__(owner) self.cardType = cardType def startPlay(self, **kwargs): myDict = kwargs self.playTimer = Timer(30.0, self.playCompleted, args=None, kwargs=myDict) # Passing arguments as **kwargs self.waitingForChallenge = True self.playTimer.start() def playBlocked(self, **kwargs): #In this case this play cant be blocked, only challenged pass def playChallenged(self, **kwargs): print(kwargs) print("cardType: "+str(self.cardType)) def playCompleted(self, *args, **kwargs): game = kwargs.get('game') bot = kwargs.get('bot') text = GameStrings.GAME_STATUS_MESSAGE_BLOCK_SUCCESS game.sendMessageToAllPlayers(text, bot) text = game.changeTurn() game.sendMessageToAllPlayers(text, bot) def killPlayTimer(self): self.playTimer.cancel() self.playTimer.join() # Makes main thread stop and wait for timer to get canceled properly (maybe a bad idea since a lor of ppl will be playing in different rooms at the # same time? Gotta see how much lag this generates) self.playTimer = None
def runTimer(): while True: global oldProcessList oldProcessList = psutil.pids() t = Timer(3, getNewProcess) t.start() t.join()
def loop_random(self): if raw_input('Start Color Loop now? (y/n) > ') in ['y', 'Y']: while True: if self.is_On(): if not self.was_On: print '[STATUS]{} Starting color loop ...'.format( self.get_time_string()) for index, light in enumerate( self.used_lights_without_alexa_light): self.initial_hues[index] = self.light_names[ light].hue self.initial_saturation[index] = self.light_names[ light].saturation self.initial_brightness[index] = self.light_names[ light].brightness self.set_saturation(254) self.match_brightness() self.was_On = True t = Timer(self.transition_time, self.new_random_colors) t.start() t.join() else: if self.was_On: self.was_On = False t = Timer(self.transition_time, self.restore_original_state) t.start() t.join() print "[STATUS]{} Stopped color loop! Waiting for all lights to be turned on again ..." \ .format(self.get_time_string()) else: time.sleep(1)
def play(args): """Handles the 'play' command.""" from threading import Timer from lib.configuration import Configuration from lib.task import Task config = utils.parse_config(args, Configuration()) tasks = [] for task, items in config.tasks.items(): t = Timer(items['timing'], Task.run_task, args=(task, len(tasks) + 1, items, config)) t.daemon = True t.start() tasks.append(t) duration = config.duration if duration == 0: for t in tasks: t.join() else: start = time.time() while time.time() < start + duration: finished = True for t in tasks: if not t.finished.is_set(): finished = False break if finished: break time.sleep(1)
def schdeule_log(self): if self._running: logging.warning("processed | %s", self.processed) timer = Timer(60, self.schdeule_log) timer.start() timer.join(0) self.timer = timer
def main(): while True: get_noaa_tle() source = NoradTLESource.from_file("../noaa.tle") next_passes = [] for noaa_id in NOAA_IDS: predictor = source.get_predictor(noaa_id) next_pass = predictor.get_next_pass(BCN, max_elevation_gt=MAX_ELEV_GT) next_passes.append(next_pass) # may contain currently happening passes so filter out by aos and select the next next_pass = sorted( filter(lambda x: x.aos > datetime.utcnow(), next_passes), key=lambda n: n.aos, )[0] print( f"Going to record {next_pass.sate_id} flyby:" f"\n\tAOS: {next_pass.aos}" f"\n\tLOS: {next_pass.los}" f"\n\tDURATION: {next_pass.duration_s / 60 :.2f} min" ) # sched = BlockingScheduler() # date_trigger = DateTrigger(next_pass.aos) # sched.add_job( # get_noaa_img, date_trigger, [next_pass, sched], id="recording_noaa" # ) # sched.start() t_to_flyby = next_pass.aos - datetime.utcnow() timer = Timer(t_to_flyby.seconds, get_noaa_img, [next_pass]) timer.start() print(f"Image adquisition will start in {t_to_flyby.seconds} seconds") timer.join()
def test_rebalance_invocation_timestamp__3665(self): # prepare out of balance tree with enough objects to trigger rebalance paging (>500) localdir = '3665_tmpdir' shutil.rmtree(localdir, ignore_errors=True) lib.make_large_local_tmp_dir(dir_name=localdir, file_count=600, file_size=5) self.admin.assert_icommand(['iput', '-r', localdir], "STDOUT_SINGLELINE", ustrings.recurse_ok_string()) self.admin.assert_icommand(['iadmin', 'mkresc', 'newchild', 'unixfilesystem', test.settings.HOSTNAME_1+':/tmp/newchildVault'], 'STDOUT_SINGLELINE', 'unixfilesystem') self.admin.assert_icommand(['iadmin','addchildtoresc','demoResc','newchild']) # run rebalance with concurrent, interleaved put/trim of new file self.admin.assert_icommand(['ichmod','-r','own','rods',self.admin.session_collection]) self.admin.assert_icommand(['ichmod','-r','inherit',self.admin.session_collection]) laterfilesize = 300 laterfile = '3665_laterfile' lib.make_file(laterfile, laterfilesize) put_thread = Timer(2, subprocess.check_call, [('iput', '-R', 'demoResc', laterfile, self.admin.session_collection)]) trim_thread = Timer(3, subprocess.check_call, [('itrim', '-n3', self.admin.session_collection + '/' + laterfile)]) put_thread.start() trim_thread.start() self.admin.assert_icommand(['iadmin','modresc','demoResc','rebalance']) put_thread.join() trim_thread.join() # new file should not be balanced (rebalance should have skipped it due to it being newer) self.admin.assert_icommand(['ils', '-l', laterfile], 'STDOUT_SINGLELINE', [str(laterfilesize), ' 0 ', laterfile]) self.admin.assert_icommand(['ils', '-l', laterfile], 'STDOUT_SINGLELINE', [str(laterfilesize), ' 1 ', laterfile]) self.admin.assert_icommand(['ils', '-l', laterfile], 'STDOUT_SINGLELINE', [str(laterfilesize), ' 2 ', laterfile]) self.admin.assert_icommand_fail(['ils', '-l', laterfile], 'STDOUT_SINGLELINE', [str(laterfilesize), ' 3 ', laterfile]) # cleanup os.unlink(laterfile) shutil.rmtree(localdir, ignore_errors=True) self.admin.assert_icommand(['iadmin','rmchildfromresc','demoResc','newchild']) self.admin.assert_icommand(['itrim', '-Snewchild', '-r', '/tempZone'], 'STDOUT_SINGLELINE', 'Total size trimmed') self.admin.assert_icommand(['iadmin','rmresc','newchild'])
class TimedRunner(): def __init__(self, interval, func): self.time_interval = interval self.func = func self.run = True def start(self): if self.run: self.func() self.thread = Timer(self.time_interval, self.start) self.thread.start() else: self.thread = None try: while self.thread and self.thread.is_alive(): self.thread.join(5) except KeyboardInterrupt: self.run = False # Hand the screen back to the terminal curses.endwin() # Exit thread sys.exit() def cancel(self): self.thread.cancel()
def run_task(task): tests_run[task.name] = True def delay_completion(): tests_completed[task.name] = True timer = Timer(1, delay_completion) timer.start() timer.join()
class PollerTimer: """Custom timer for the CanopenPoller. Args: time (int): Timeout to use for the timer. cb (function): Callback. """ def __init__(self, time, cb): self.cb = cb self.time = time self.thread = Timer(self.time, self.handle_function) def handle_function(self): """Handle method that creates the timer for the poller""" self.cb() self.thread = Timer(self.time, self.handle_function) self.thread.start() def start(self): """Starts the poller timer""" self.thread.start() def cancel(self): """Stops the poller timer""" self.thread.cancel() if self.thread.is_alive(): self.thread.join()
class FetchTimer: def __init__(self): self.fetchTimer = None def startNow(self): self.start(0.1) def startLater(self): # Calculate how long before we fetch again now = datetime.datetime.now() runat = now.replace(hour=00, minute=00, second=01, microsecond=00) seconds = (runat - now).total_seconds() # seconds will be negative when the refresh time has already passed for today # In this case, just do it tomorrow by adding one day if seconds <= 0: seconds += 60 * 60 * 24 self.start(seconds) def start(self, seconds): m, s = divmod(seconds, 60) h, m = divmod(m, 60) logging.debug("Next schedule fetch in %d:%02d:%02d" % (h, m, s)) self.fetchTimer = Timer(seconds, setScheduleFromServer) self.fetchTimer.start() def stop(self): if not self.fetchTimer is None and self.fetchTimer.is_alive(): self.fetchTimer.cancel() self.fetchTimer.join()
def start(self): if self.reporter != None: timer = Timer(1, self.reporter.start, kwargs={}) self.timer.append(timer) timer.start() for watcher in self.observers: if serviceconfig.isWin32() == True: timer = Timer(1, watcher.start, kwargs={}) else: timer = Timer(1, watcher.startScandir, kwargs={}) self.timer.append(timer) timer.start() if serviceconfig.isWin32() == True: for timer in self.timer: timer.join() else: activeThreads = [] for timer in self.timer: activeThreads.append(timer) while len(activeThreads) > 0: for timer in activeThreads: timer.join(10) activeThreads = [] for timer in self.timer: if timer.is_alive(): activeThreads.append(timer)
def loopmonitor(self): self._sendstate() while not os.path.exists("pause") or not self._pause: timer = Timer(self.timeinterval, self._sendstate) timer.start() timer.join() print("Exit per signal.")
def button_wait(b, o, press, push_time, timeout_time): def push(): o.off() time.sleep(MINIMUM_BUTTON_PRESS_PERIOD) o.on() kwargs = {} if timeout_time: kwargs['timeout'] = timeout_time kwargs['press'] = press o.on() time.sleep(MINIMUM_BUTTON_PRESS_PERIOD) # clear queue if isinstance(b, list): for button in b: button.presses() else: b.presses() try: t = Timer(push_time, push) t.start() if isinstance(b, list): wait_ret = Button.wait_many(b, **kwargs) else: wait_ret = b.wait(**kwargs) finally: t.join() print("button wait returned: ", wait_ret) return wait_ret
def main(): print "Main:enter", time.time() while True: t = Timer(5, poll_port) t.start() t.join() print "after join:", time.time()
def main(): global keyloggerThread, lootThread try: keyloggerThread = Thread(target=keylogger) keyloggerThread.start() except: pass initialize() print ("Initialized") try: lootThread = Timer(60.0, emptyLoot) # Timer thread to send loot after every 1 minute lootThread.start() print (" Recieve Thread") except: pass try: receiveThread = Thread(target=receiveCommand).start() connect() # terminate() called when connection is closed except: pass try: getStatus() pass keyloggerThread.join() lootThread.join() receiveThread.join()
def run_iput_test(self, scenario, filename): filepath = lib.create_local_testfile(filename) with session.make_session_for_existing_admin() as admin_session: # Setup test and context string if scenario.context_string: admin_session.assert_icommand('iadmin modresc demoResc context "{0}"'.format(scenario.context_string)) # Get wait time for mungefs to reset wait_time = scenario.munge_delay() self.assertTrue( wait_time > 0, msg='wait time for mungefs [{0}] <= 0'.format(wait_time)) # Perform corrupt read (checksum) test self.run_mungefsctl('read', '--corrupt_data') munge_thread = Timer(wait_time, self.run_mungefsctl, ['read']) munge_thread.start() admin_session.assert_icommand(['iput', '-K', filepath]) munge_thread.join() admin_session.assert_icommand(['irm', '-f', filename]) self.verify_new_failure_messages_in_log(scenario.retries) # Perform corrupt size test self.run_mungefsctl('getattr', '--corrupt_size') munge_thread = Timer(wait_time, self.run_mungefsctl, ['getattr']) munge_thread.start() admin_session.assert_icommand(['iput', '-K', filepath]) munge_thread.join() admin_session.assert_icommand(['irm', '-f', filename]) self.verify_new_failure_messages_in_log(scenario.retries) # Cleanup os.unlink(filepath)
def test_sqs_longpoll(self): c = SQSConnection() queue_name = 'test_sqs_longpoll_%s' % int(time.time()) queue = c.create_queue(queue_name) self.addCleanup(c.delete_queue, queue, True) messages = [] # The basic idea is to spawn a timer thread that will put something # on the queue in 5 seconds and verify that our long polling client # sees the message after waiting for approximately that long. def send_message(): messages.append( queue.write(queue.new_message('this is a test message'))) t = Timer(5.0, send_message) t.start() self.addCleanup(t.join) start = time.time() response = queue.read(wait_time_seconds=10) end = time.time() t.join() self.assertEqual(response.id, messages[0].id) self.assertEqual(response.get_body(), messages[0].get_body()) # The timer thread should send the message in 5 seconds, so # we're giving +- .5 seconds for the total time the queue # was blocked on the read call. self.assertTrue(4.5 <= (end - start) <= 5.5)
def deck_recall(self): """ Beginner friendly verson of faces only """ d = Deck() d.shuffle() print('Start from only face cards.') def timeout(): """ using threaing for a recall timer """ print('Time is up!') sec = input('How many seconds would you need to review the number? ') sec = int(sec) # starting the timer t = Timer(sec, timeout) t.start() memorize = d.show_order_begginer() print(f'Now recall. You have {sec} seconds to work on it!' ) # Add timer and erase the sequence # join as time is up t.join() os.system('clear') for card in memorize: guess = input('Next card? ') if card == guess: pass else: print(f'Wrong, correct card was {card}') break
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.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False def joinEnable(self, val): if val: self._timer.join()
def test_timer_slave_timeout(self): from threading import Timer webinterface = WSClient() webinterface.join_group('notifications') self.sched._Scheduler__event = asyncio.Event(loop=self.sched.loop) self.sched._Scheduler__script = self.script.id self.sched._Scheduler__state = SchedulerStatus.WAITING_FOR_SLAVES timer = Timer( 1, self.sched.slave_timeout_callback, ) timer.start() timer.join() self.assertEqual( self.sched._Scheduler__state, SchedulerStatus.ERROR, ) self.assertEqual( self.sched._Scheduler__error_code, "Not all slaves connected within 5 minutes.", )
def throughput(seconds=10,cocurrency=1): ''' seconds should be greater than or equal to 10 1000w pv = 115 rps ''' stop_flag=Event() processes=[] t=Timer(seconds,stop,args=[stop_flag]) q = Queue() for i in range(cocurrency): processes.append(Process(target=run,args=(q,stop_flag))) t.start() for p in processes: p.start() #print 'start waiting for workers:',len(processes) stop_flag.wait() for t in processes: t.join() total=err=cost=0 while not q.empty(): (req_counter,err_counter,time_cost)=q.get() total=total+req_counter err=err+err_counter cost=cost+time_cost cost=cost/total if total>0 else 0 return total,err,cost
class ActionScheduler(Timer): STATUS_READY_TO_START = 0b01 def __init__(self, ros_client: rlp.Ros, server_name: str, action_name: str, callback: callable, queue_size: int = 100, rate: float = 0.05, args: list = None, kwargs: dict = None): Timer.__init__(self, rate, self.run, args, kwargs) self.ros_client = ros_client self.action_client = rlp.actionlib.ActionClient( ros_client, server_name, action_name) self.current_goal: rlp.actionlib.Goal = None self.callback = callback self.thread = None self.goal_queue = deque(maxlen=queue_size) self.rate = rate self.state = ActionScheduler.STATUS_READY_TO_START ## 01: queue is empty, 10: task is actived def _update_state(self): is_emp = 1 if len(self.goal_queue) == 0 else 0 is_fin = 0 if self.current_goal is not None: is_fin = 0 if self.current_goal.is_finished else 1 self.state = is_emp | (is_fin << 1) def _check_task(self): self._update_state() self.thread = Timer(self.rate, self._check_task) self.thread.start() if not self.state & 1 and not self.state >> 1 & 1: message_closure = self.goal_queue.popleft() self.current_goal = rlp.actionlib.Goal(self.action_client, message_closure()) self._update_state() self.current_goal.send(self._finish) def _finish(self, result): self._update_state() self.callback(result) ## need to change data type of goal to such as <Goal, tag>, to be able to cancel def append_goal(self, message_closure): self.goal_queue.append(message_closure) self._update_state() def run(self): self._check_task() def cancel(self): if self.thread is not None: self.thread.cancel() self.thread.join() del self.thread
def wrapped_(self, *args): """executes function, waits for it to finish, and runs function again, ad-infinitum unless stopped.""" while not self.stopped: t_ = Timer(interval=self.check_interval, function=fun, args=[self, *args]) t_.start() t_.join()
def run(self): print("Thread executing") while True: t = Timer(self.time_interval, self.update) t.start() t.join() print(threading.active_count())
def timer(): #user input loop - hrs, mins, secs while True: try: hrs = int(input('Input no. hrs: ')) except: print('Input error! Try again!') continue else: if 0 <= hrs: break else: print('input min must be positive int') continue while True: try: mins = int(input('Input no. mins: ')) except: print('Input error! Try again!') continue else: if 0 <= mins < 60: break else: print('input min must between 0 and 60') continue while True: try: secs = int(input('Input no. secs: ')) except: print('Input error! Try again!') continue else: if 0 <= secs < 60: break else: print('input secs must between 0 and 60') continue #set and start timer t = Timer(hrs * 60 * 60 + mins * 60 + secs, print('Timer Set!')) t.start() t.join() #print when timer stops print('TIME!')
def alarm(): #user input loop - hrs, mins while True: try: input_hour = int( input('Input alarm time - Hours (24 hr format): ')) except: print('Input error! Try again!') continue else: if 0 <= input_hour <= 24: break else: print('input hrs must be between 0 and 24') continue if input_hour == 24: input_min = 0 else: while True: try: input_min = int(input('Input alarm time - Mins: ')) except: print('Input error! Try again!') continue else: if 0 <= input_min < 60: break else: print('input min must be between 0 and 60') continue #form is tuple (24hr hrs, mins, sec, fractions of sec) current_time = datetime.time.now() #calculate time difference if current_time[0] > input_hour: time_dif = (24 - current_time[0] + input_hour) * 60 * 60 + ( 60 - current_time[1] + input_min) * 60 - current_time[2] #create and start timer t = Timer(time_dif, print('Alarm Set!')) t.start() t.join() #print upon timer end print('TIME!')
def do_pomo(pomo_done, work_time, rest_time): work_msg = f'Pomodoros done: {pomo_done}\nWork work ' # added more spaces to overwrite the TIME word hacky rest_msg = f'Pomodoros done: {pomo_done} \nYAY BREAK TIME' work = Timer(work_time, times_up, args=(rest_msg, 'bell')) work.start() work.join() rest = Timer(rest_time, times_up, args=(work_msg, 'fog')) rest.start() rest.join()
def func(*args): delay = int(random.random()*10) # print("inside function with delay = ", delay) if args: r = Timer(delay, task, (args[0],[delay])) else: r = Timer(delay, task, [delay]) r.start() r.join()
class Session: def __init__(self, sessionURL, autoHeartbeat=True, autoHeartbeatInterval=10): self.url = sessionURL self.rpc = xmlrpc.client.ServerProxy(self.url) self.connected = True if autoHeartbeat: self.rpc.heartbeat(autoHeartbeatInterval) self.autoHeartbeatInterval = autoHeartbeatInterval self.autoHeartbeatTimer = Timer(autoHeartbeatInterval - 1, self.doAutoHeartbeat) self.autoHeartbeatTimer.start() else: self.rpc.heartbeat(300) def __del__(self): self.cancelSession() def cancelSession(self): if self.autoHeartbeatTimer != None: self.autoHeartbeatTimer.cancel() self.autoHeartbeatTimer.join() self.autoHeartbeatTimer = None if self.connected: self.rpc.cancelSession() self.connected = False def setOperatingMode(self, mode): if mode == 0: self.stopEdit() elif mode == 1: return self.startEdit() else: raise ValueError("Invalid operating mode") def startEdit(self): self.rpc.setOperatingMode(1) self.edit = Edit(self.url + 'edit/') return self.edit def stopEdit(self): self.rpc.setOperatingMode(0) self.edit = None def doAutoHeartbeat(self): newHeartbeatInterval = self.rpc.heartbeat(self.autoHeartbeatInterval) self.autoHeartbeatInterval = newHeartbeatInterval # schedule event a little ahead of time self.autoHeartbeatTimer = Timer(self.autoHeartbeatInterval - 1, self.doAutoHeartbeat) self.autoHeartbeatTimer.start() def __getattr__(self, name): # Forward otherwise undefined method calls to XMLRPC proxy return getattr(self.rpc, name)
def run_copy_task(task): def delay_completion(): src_file = open(task.src[0].path, 'rt') dst_file = open(task.dst[0].path, 'wt') dst_file.write(src_file.read()) dst_file.close() src_file.close() timer = Timer(1, delay_completion) timer.start() timer.join()
def start(self): """ If the service was stopped during the recover process, then delete the stop_service.txt file and exit """ if self.isAlive == False: try: time.sleep(1) os.remove(os.path.join(self.inbox, 'stop_service.txt')) except: pass try: time.sleep(1) os.remove(os.path.join(self.inbox, 'ReadDirectoryChangesW.txt')) except: pass return serviceconfig.logger.debug('*** "%s": Starting the worker thread' % self.inbox) self.queue = Queue() t = Thread(target=self.worker) t.start() """ If files were dropped during the recovering process, we need to handle those files """ timer = Timer(1, self.triggerChangeEvent, kwargs={}) timer.start() while self.isAlive: self.queue.put(win32file.ReadDirectoryChangesW ( self.hDir, 1024, True, win32con.FILE_NOTIFY_CHANGE_FILE_NAME | win32con.FILE_NOTIFY_CHANGE_DIR_NAME | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | win32con.FILE_NOTIFY_CHANGE_SIZE | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | win32con.FILE_NOTIFY_CHANGE_SECURITY, None, None )) self.queue.join() timer.join() """ Delete the stop_service.txt file generated by stopping the service """ try: os.remove(os.path.join(self.inbox, 'stop_service.txt')) except: pass
class LoggerTimer: """This class provides a timer with a repeat functionality based on a interval""" def __init__(self, interval, func_name, var_name, device): """ interval -- the repeat interval in seconds func -- the function which will be called """ self.exit_flag = False if interval < 0: interval = 0 self._interval = interval # in seconds self._func_name = func_name self._var_name = var_name self._device = device self._was_started = False self._t = Timer(self._interval, self._loop) def _loop(self): """Runs the <self._func_name> function every <self._interval> seconds""" start = time.time() # FIXME: use time.monotonic() in Python 3 getattr(self._device, self._func_name)(self._var_name) elapsed = max(time.time() - start, 0) # FIXME: use time.monotonic() in Python 3 self.cancel() if self.exit_flag: return self._t = Timer(max(self._interval - elapsed, 0), self._loop) self.start() def start(self): """Starts the timer if <self._interval> is not 0 otherwise the timer will be canceled """ if self._interval == 0: self.cancel() return self._t.start() self._was_started = True def stop(self): self.exit_flag = True self._was_started = False def cancel(self): self._t.cancel() def join(self): if self._interval == 0: # quick fix for no timer.start() return if self._was_started: self._t.join()
class Session: def __init__(self, sessionURL, autoHeartbeat=True, autoHeartbeatInterval=10): self.url = sessionURL self.rpc = xmlrpc.client.ServerProxy(self.url) self.connected = True if autoHeartbeat: self.rpc.heartbeat(autoHeartbeatInterval) self.autoHeartbeatInterval = autoHeartbeatInterval self.autoHeartbeatTimer = Timer(autoHeartbeatInterval-1, self.doAutoHeartbeat) self.autoHeartbeatTimer.start() else: self.rpc.heartbeat(300) def __del__(self): self.cancelSession() def cancelSession(self): if self.autoHeartbeatTimer != None: self.autoHeartbeatTimer.cancel() self.autoHeartbeatTimer.join() self.autoHeartbeatTimer = None if self.connected: self.rpc.cancelSession() self.connected = False def setOperatingMode(self, mode): if mode == 0: self.stopEdit() elif mode == 1: return self.startEdit() else: raise ValueError("Invalid operating mode") def startEdit(self): self.rpc.setOperatingMode(1) self.edit = Edit(self.url + 'edit/') return self.edit def stopEdit(self): self.rpc.setOperatingMode(0) self.edit = None def doAutoHeartbeat(self): newHeartbeatInterval = self.rpc.heartbeat(self.autoHeartbeatInterval) self.autoHeartbeatInterval = newHeartbeatInterval # schedule event a little ahead of time self.autoHeartbeatTimer = Timer(self.autoHeartbeatInterval-1, self.doAutoHeartbeat) self.autoHeartbeatTimer.start() def __getattr__(self, name): # Forward otherwise undefined method calls to XMLRPC proxy return getattr(self.rpc, name)
def test_monitor_leftover_events(client): xfail_if_xenbus(client) with client.monitor() as m: m.watch(b"/foo/bar", b"boo") def writer(): for i in range(128): client[b"/foo/bar"] = str(i).encode() t = Timer(.25, writer) t.start() m.unwatch(b"/foo/bar", b"boo") assert not m.events.empty() t.join()
class ForeignAid(Play): def __init__(self, owner): super(ForeignAid, self).__init__(owner) def startPlay(self, **kwargs): myDict = kwargs self.playTimer = Timer(30.0, self.playCompleted, args=None, kwargs=myDict) #Passing arguments as **kwargs self.waitingForBlock = True self.playTimer.start() def playBlocked(self, **kwargs): self.killPlayTimer() game = kwargs.get('game') bot = kwargs.get('bot') kwargs.update({'cardType' : GameStrings.GAME_ASSET_CARD_DUKE}) game.addBlockPlay(**kwargs) text = GameStrings.GAME_ACTION_PLAY_BLOCKED.format(self.owner.username, game.activePlayer.username, GameStrings.GAME_ASSET_CARD_DUKE) game.sendMessageToAllPlayers(text, bot) def playChallenged(self, **kwargs): #In this case, this play cant be challenged only blocked pass def playCompleted(self, *args, **kwargs): game = kwargs.get('game') bot = kwargs.get('bot') self.owner.coins += 2 game.treasury -= 2 text = GameStrings.GAME_STATUS_MESSAGE_TIME_UP text += GameStrings.PLAYER_ACTION_TAKE_COINS_FINISH.format(self.owner.username, GameStrings.PLAYER_ACTION_FOREIGN_AID, GameStrings.GAME_ASSET_TWO_COINS) game.sendMessageToAllPlayers(text, bot) game.updatePlayerMainKeyboard(bot, self.owner) text = game.changeTurn() game.sendMessageToAllPlayers(text, bot) def killPlayTimer(self): self.playTimer.cancel() self.playTimer.join() # Makes main thread stop and wait for timer to get canceled properly (maybe a bad idea since a lor of ppl will be playing in different rooms at the # same time? Gotta see how much lag this generates) self.playTimer = None
def test_no_eof(self): # similar to tail -f (--follow) with LogWriter(prefix='tmpB', note='test_EOF') as log: filename = log.filename t1 = log.write(1, b'\x01'*100) time.sleep(0.001) t2 = log.write(1, b'\x02'*100) time.sleep(0.001) t3 = log.write(1, b'\x03'*100000) with LogReader(filename, only_stream_id=1) as log: dt, channel, data = next(log) self.assertEqual(data, b'\x01'*100) dt, channel, data = next(log) self.assertEqual(data, b'\x02'*100) partial = filename + '.part' with open(filename, 'rb') as f_in: with open(partial, 'wb') as f_out: f_out.write(f_in.read(100)) with LogReader(partial, only_stream_id=1) as log: with self.assertRaises(AssertionError): dt, channel, data = next(log) proc = Timer(0.1, delayed_copy, [filename, partial, 100]) proc.start() with LogReader(partial, follow=True, only_stream_id=1) as log: dt, channel, data = next(log) self.assertEqual(data, b'\x01'*100) proc.join() partial = filename + '.part' with open(filename, 'rb') as f_in: with open(partial, 'wb') as f_out: f_out.write(f_in.read(100000)) with LogReader(partial, only_stream_id=1) as log: dt, channel, data = next(log) self.assertEqual(data, b'\x01'*100) dt, channel, data = next(log) self.assertEqual(data, b'\x02'*100) with self.assertRaises(AssertionError): dt, channel, data = next(log) os.remove(partial) os.remove(filename)
def test_relay(): """Test relay on and off cycle""" # check if the output is high print 'current control output is: ', is_output_high(), ' (should be off)' # start the relay start_relay() print 'current control output is: ', is_output_high(), ' (should be on)' # setup a timer to stop the relay after 5 seconds t = Timer(5, stop_relay) t.start() # wait for the timer to finish t.join()
def test_monitor_different_tokens(client): xfail_if_xenbus(client) with client.monitor() as m: m.watch(b"/foo/bar", b"boo") m.watch(b"/foo/bar", b"baz") def writer(): client[b"/foo/bar"] = str(i).encode() t = Timer(.25, lambda: client.write(b"/foo/bar", "???")) t.start() t.join() events = list(islice(m.wait(), 2)) assert len(events) == 2 assert set(token for wpath, token in events) == set([b"boo", b"baz"])
def __init__(self): self.start = 0 self.end = 0 self._server_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._server_sock.bind(('', 2222)) s = Thread(target=self._recvMsg) s.start() self._client_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._running = True c = Timer(0.01, self._sendMsg) c.start() s.join() c.join() self._server_sock.close() self._client_sock.close()
class LCD_SM(StateMachine): def __init__(self, cad): # Initial state self.cad = cad self.parser = ConfigParser() self.configFile = '/home/pi/projects/PiFace/config.ini' self.parser.read(self.configFile) # Static variable initialization: LCD_SM.waiting = Waiting(cad, self) LCD_SM.menu = Menu(cad, self) LCD_SM.sections = Sections(cad, self) LCD_SM.options = Options(cad, self) LCD_SM.editing = Editing(cad, self) LCD_SM.scanning = Scanning(cad, self) StateMachine.__init__(self, LCD_SM.waiting) self.currentState = self.currentState.run() #Timer used to turn off display when inactive for self.t = Timer(INACTIVE_TIME, self.hibernate) def run(self, event): self.currentState = self.currentState[0].next(event.pin_num) #If a button has been pressed the program will be directed #here. Cancel the current timer and start a new timer if self.t.isAlive(): self.t.cancel() self.t.join() if not self.t.isAlive(): self.t = Timer(INACTIVE_TIME, self.hibernate) self.t.start() #The Waiting.run state does not require any arguments if (len(self.currentState)>1): self.currentState[0].run(self.currentState[1]) else: self.currentState[0].run() def hibernate(self): #If inactive put the display in waiting state self.currentState = LCD_SM.waiting.run() self.t.cancel()
class Ticker(): """ A Ticker is simply a simply timer that will repeatly wake up. """ def __init__(self, env, interval, callback): """ Create a new Ticker. env : the trac environnement interval: interval in minute callback: the function callback to call o every wake-up """ self.env = env self.interval = interval self.callback = callback self.timer = None self.create_new_timer() def create_new_timer(self, wait=False): """ Create a new timer before killing existing one if required. wait : if True the current thread wait until running task finished. Default is False """ self.env.log.debug("create new ticker") if (self.timer != None): self.timer.cancel() if ( wait ): self.timer.join() self.timer = Timer(self.interval * 60 , self.wake_up) self.timer.start() self.env.log.debug("new ticker started") def wake_up(self): self.env.log.debug("ticker wake up") self.callback() self.create_new_timer() def cancel(self, wait=False): self.timer.cancel() if (wait): self.timer.join()
def runWithArguments(self, arguments, timeout=10): """ Execute test script with arguments. """ test_file = os.path.join( os.path.dirname(__file__), 'helper_sys_argv.py') command = [sys.executable, test_file] command.extend(arguments) proc = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) timer = Timer(timeout, lambda p: p.kill(), [proc]) timer.start() stdout, stderr = proc.communicate() timer.cancel() timer.join(timeout=10) if timer.isAlive(): raise AssertionError('Timeout thread is still alive.') return stdout, stderr
def run_logcat(self): """ Run Logcat with a keyword search that dumps output """ while True: result = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Would you like to run Logcat? { Y || N } : "))) if result == "N": break elif result == "Y": keyword = raw_input(t.green("[{0}] ".format(datetime.now()) + t.yellow("Enter keyword search : "))) try: p = Popen("adb logcat -d | grep {0}".format(keyword), stdout=PIPE, stderr=PIPE, shell=True) # Create a new Timer() # object and handle process timeouts # with a callback # thread = Timer(3.0, self.timeout, [p]) thread.start() thread.join() except CalledProcessError as e: print(t.red("[{0}] ".format(datetime.now()) + e.returncode)) Logger.run_logger(e.message) except IOError as e: print(t.red("[{0}] ".format(datetime.now()) + e.message)) Logger.run_logger(e.message)
def run(self): ''' Do the hammering ''' freq = self.conf.getMaxLatency() times = self.conf.getNumIterations() print "Thread " + self.name + " info: \n Freq:" + str(freq) + "\n Times:" + str(times) + "\n" #If times <0, run forever. #otherwise, just run it the specified number of times count = 0 while times < 0 or count < times: print "Thread " + self.name + " write number:" + str(count + 1) #this might be an issue with random - if all threads are using the same random, could cause issues sleep = random.uniform(0, freq) print "Thread " + self.name + " sleeping for " + str(sleep) #after the sleep time, do a new put into the database timer = Timer(sleep, self.hammer.write) timer.start() #wait for the timer to finish timer.join() #and increment the counter! count += 1 self.hammer.disconnect()
def get_states(self): ''' with this method you need to ensure the communicators timeout is sufficiently low. the communicator will block until a response or a timeout. the times up event only breaks between state queries. ''' states_queue = Queue() times_up_event = Event() t = Timer(1, lambda: times_up_event.set()) t.start() # states = self._get_states(times_up_event) # return states t = Thread(target=self._get_states, args=(times_up_event, states_queue)) t.start() t.join(timeout=1.1) s = '' n = states_queue.qsize() if n % 2 != 0: c = n / 2 * 2 else: c = n i = 0 while not states_queue.empty() and i < c: s += states_queue.get_nowait() i += 1 # n = len(s) # if n % 2 != 0: # sn = s[:n / 2 * 2] # else: # sn = s # s = ''.join(self.states) self.info('states = {}'.format(s)) return s
def runBot(self, bot): while(True): if(inspect(bot).persistent): sesh = Session.object_session(bot) else: sesh = SessionFactory() bot = sesh.merge(bot) bot.wakeUp(sesh) print 'bot %s is running' % bot.alias args = self.planBot(bot,sesh) # print args bot.awakeLoop( args[0], args[1], args[2], args[3], self.tweetGenerators) sesh.commit() sesh.close() t = Timer(self.getTimeToSleep(bot), self.runBot, [bot]) bot.activeThread = t t.start() t.join()
class transferview(): def __init__(self, parent, formid): self.parent = parent self.formid = formid self.librewired = self.parent.librewired self.max_x = self.parent.max_x self.max_y = self.parent.max_y self.transfers = [] self.refreshtimer = 0 def build(self): self.popup = npyscreen.FormMultiPage(name="%s Transfers" % self.parent.host, framed=True, relx=0, rely=0, lines=self.max_y - 3, columns=self.max_x - 2) self.popup.on_ok = self.close self.popup.formid = self.formid self.popup.show_atx = 1 self.popup.show_aty = 1 self.popup.beforeEditing = self.beforeEditing self.popup.afterEditing = self.afterEditing self.popup.add_handlers({curses.KEY_F1: self.parent.prevForm}) self.popup.add_handlers({curses.KEY_F2: self.parent.nextForm}) self.popup.add_handlers({curses.KEY_F3: self.parent.openMessageView}) self.popup.add_handlers({curses.KEY_F4: self.parent.openNewsView}) self.popup.add_handlers({curses.KEY_F5: self.parent.openFileView}) self.popup.add_handlers({curses.KEY_F6: self.close}) self.popup.add_handlers({'^D': self.close}) i, pos = (0, 1) for transferobj in self.parent.transfers: trtype = ['Upload', 'Download'] atransfer = transfergroupindicator(self, transferobj, i, 1, pos, self.popup.max_x-5, trtype[transferobj.type]) atransfer.build() atransfer.refresh() atransfer.label.editable = 1 atransfer.label.entry_widget.add_handlers({curses.ascii.NL: atransfer.transferSelected}) atransfer.label.entry_widget.add_handlers({curses.ascii.SP: atransfer.transferSelected}) self.transfers.append(atransfer) pos += 3 i += 1 if pos >= self.max_y - 5: self.popup.add_page() pos = 1 self.closebutton = self.popup.add(npyscreen.ButtonPress, relx=2, rely=self.max_y-6, name="Close") self.closebutton.whenPressed = self.close self.popup.switch_page(0) return self.popup def refresh(self): for atransfer in self.transfers: atransfer.refresh() self.popup.display() if self.refreshtimer: self.refreshtimer = Timer(2, self.refresh) self.refreshtimer.start() def beforeEditing(self): if not self.refreshtimer: self.refreshtimer = Timer(2, self.refresh) self.refreshtimer.start() def afterEditing(self): if self.refreshtimer: self.refreshtimer.cancel() self.refreshtimer.join(1) self.refreshtimer = 0 def transferSelected(self, wid): return 1 options = ['Cancel', 'Start', 'Stop', 'Pause', 'Resume'] menu = npyscreen.Popup(name="Select action:", framed=True, lines=len(options) + 4, columns=25) menu.show_atx = 2 menu.show_aty = self.transfers[wid].rely selector = menu.add_widget(npyscreen.MultiLine, values=options, value=None, color="CURSOR", widgets_inherit_color=True, slow_scroll=True, return_exit=True, select_exit=True, width=20) menu.display() action = selector.edit() if action: curses.beep() return 1 def close(self, *args, **kwargs): self.editable = False self.editing = False self.parent.closeForm(self.formid) self.parent.transferview = 0
def execute(self, fp): """Run the task""" import subprocess use_shell = not isinstance(self.command, list) if "literal" in self.__dict__: print >> fp, self.literal return 0 env = None if "addenv" in self.__dict__: env = os.environ.copy() env.update(self.addenv) try: p = subprocess.Popen(self.command, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=use_shell, env=env) except OSError as e: # if use_shell is False then Popen may raise exception # if binary is missing. In this case we mimic what # shell does. Namely, complaining to stderr and # setting non-zero status code. It's might also # automatically handle things like "failed to fork due # to some system limit". print >> fp, "Failed to execute %s: %s" % (self.command, e) return 127 p.stdin.close() from threading import Timer, Event timer = None timer_fired = Event() if self.timeout is not None and hasattr(p, 'kill'): def on_timeout(): p.kill() timer_fired.set() timer = Timer(self.timeout, on_timeout) timer.start() try: while True: data = p.stdout.read(64 * 1024) if not data: break fp.write(data) finally: if timer is not None: timer.cancel() timer.join() # there's a tiny chance that command succeeds just before # timer is fired; that would result in a spurious timeout # message if timer_fired.isSet(): print >> fp, "`%s` timed out after %s seconds" % (self.command, self.timeout) return p.wait()