Python threading.Timer() Examples

The following are 30 code examples for showing how to use threading.Timer(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: svviz   Author: svviz   File: web.py    License: MIT License 6 votes vote down vote up
def run(port=None):
    import webbrowser, threading

    if port is None:
        port = getRandomPort()

    # load()
    url = "http://127.0.0.1:{}/".format(port)
    logging.info("Starting browser at {}".format(url))
    # webbrowser.open_new(url)

    threading.Timer(1.25, lambda: webbrowser.open(url) ).start()

    app.run(
        port=port#,
        # debug=True
    ) 
Example 2
Project: sanic   Author: huge-success   File: test_reloader.py    License: MIT License 6 votes vote down vote up
def test_reloader_live(runargs, mode):
    with TemporaryDirectory() as tmpdir:
        filename = os.path.join(tmpdir, "reloader.py")
        text = write_app(filename, **runargs)
        proc = Popen(argv[mode], cwd=tmpdir, stdout=PIPE, creationflags=flags)
        try:
            timeout = Timer(5, terminate, [proc])
            timeout.start()
            # Python apparently keeps using the old source sometimes if
            # we don't sleep before rewrite (pycache timestamp problem?)
            sleep(1)
            line = scanner(proc)
            assert text in next(line)
            # Edit source code and try again
            text = write_app(filename, **runargs)
            assert text in next(line)
        finally:
            timeout.cancel()
            terminate(proc)
            with suppress(TimeoutExpired):
                proc.wait(timeout=3) 
Example 3
Project: Jike-Metro   Author: Sorosliu1029   File: client.py    License: MIT License 6 votes vote down vote up
def __init__(self, sync_unread=False):
        self.auth_token = read_token()
        if self.auth_token is None:
            self.auth_token = login()
            try:
                write_token(self.auth_token)
            except IOError:
                pass
        self.jike_session = JikeSession(self.auth_token)

        self.collection = None
        self.news_feed = None
        self.following_update = None

        self.unread_count = 0
        self.timer = None
        if sync_unread:
            self.timer = Timer(
                CHECK_UNREAD_COUNT_PERIOD,
                check_unread_count_periodically,
                args=(self,)
            ).start()

        self.notified_topics = ['all']
        self.notified_users = ['all'] 
Example 4
Project: pynpuzzle   Author: mahdavipanah   File: pynpuzzle.py    License: MIT License 6 votes vote down vote up
def stop_button_cmd():
    """
    Stop button click handler
    """
    # Do some routines for stopping calculation
    calculation_stop()
    # Stop algorithm's process
    search_process.terminate()
    output_pipe.close()
    # Stop timer thread and stop refreshing status bar
    timer_event.set()
    # Clear status labels
    threading.Timer(0.1, max_ram_var.set, args=('',)).start()
    threading.Timer(0.1, cpu_var.set, args=('',)).start()
    threading.Timer(0.1, ram_var.set, args=('',)).start()


# Action buttons
#
# Output stop widget and it's border frame 
Example 5
Project: BitUtils   Author: tangible-idea   File: price_tracking.py    License: MIT License 6 votes vote down vote up
def FoundANewCoinEvent(newCoin):    
    global E_MODE
    global PURCHARSED_COIN_NAME

    print("FoundANewCoinEvent(newCoin)")
    E_MODE = 1    # change mode into TRADING

    onlyEngCoinName = re.sub(r"[^A-Za-z]+", '', newCoin)
    sendTelegramMsg("새로운 코인 상장 발견 : " + newCoin +", [" + onlyEngCoinName +"]로 비트렉스 시장 검색시작.")
    
    # buy 95% of current balance at bittrex
    affordable, savedRate= HowManyCoinYouCanBuyWithMyBalance("BTC", onlyEngCoinName)
    targetCoinName, Quantity_request= BuyLimit_PercentageOfMyBalance("BTC", onlyEngCoinName, affordable, savedRate, 0.95)

    PURCHARSED_COIN_NAME = targetCoinName # save purchased name of coin
    sendTelegramMsg("[" + targetCoinName +"]코인을 " + str(Quantity_request) +"만큼 매수 시도했음.")
    
    t = Timer(600, SellAgain)
    t.start() # after x seconds, sell again 
Example 6
Project: BitUtils   Author: tangible-idea   File: tele_channel_tracker2.py    License: MIT License 6 votes vote down vote up
def FoundLeadingSignal(TargetCoinName):
    global E_MODE
    global PURCHARSED_COIN_NAME
    # buy 95% of current balance at bittrex
    affordable, savedRate= HowManyCoinYouCanBuyWithMyBalance("BTC", TargetCoinName)
    _targetCoinName, Quantity_request, Price_request, err_msg= BuyLimit_PercentageOfMyBalance("BTC", TargetCoinName, affordable, savedRate, 0.95)

    if savedRate == None:
        sendTelegramMsg("[" + _targetCoinName +"]코인을 구매하는데 실패했음. \nbittrex에 없는 코인일 가능성 확인바람.")
    else:
        if Quantity_request == 0:
            sendTelegramMsg("[" + _targetCoinName +"]코인을 구매하는데 실패했음. \n에러명 : " + err_msg + "\n그래도 sell limit 시도는 함.")
        else:
            PURCHARSED_COIN_NAME = _targetCoinName # save purchased name of coin
            sendTelegramMsg("[" + _targetCoinName +"]코인을 " + str(Quantity_request) +"만큼 매수 시도했음. \n매수 시도 가격 : {0:.8f}".format(Price_request))
    
        # normally, 80secs to 100secs go high
        t = Timer(90, SellAgain)
        t.start() # after x seconds, sell again 
Example 7
Project: browserscope   Author: elsigh   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def GvizTableData(request):
    """Returns a string formatted for consumption by a Google Viz table."""
    #def throw_deadline():
    #    logging.info('MANUAL THROW!! DeadlineExceededError DeadlineExceededError')
    #    raise DeadlineExceededError
    #t = Timer(15.0, throw_deadline)

    test_set = None
    category = request.GET.get('category')
    if not category:
        return http.HttpResponseBadRequest('Must pass category=something')

    test_set = all_test_sets.GetTestSet(category)
    if not test_set:
        return http.HttpResponseBadRequest(
            'No test set was found for category=%s' % category)

    formatted_gviz_table_data = GetStats(request, test_set, 'gviz_table_data')
    return http.HttpResponse(formatted_gviz_table_data) 
Example 8
Project: EvalNE   Author: Dru-Mara   File: util.py    License: MIT License 6 votes vote down vote up
def run(cmd, timeout, verbose):
    if verbose:
        sto = None
        ste = None
    else:
        devnull = open(os.devnull, 'w')
        sto = devnull
        ste = devnull
    # Alternative without timeout
    # subprocess.run(cmd, shell=True, stdout=sto, stderr=ste)
    proc = Popen(shlex.split(cmd), stdout=sto, stderr=ste)
    timer = Timer(timeout, proc.kill)
    try:
        timer.start()
        proc.communicate()
    finally:
        if proc.poll() != 0:
            raise TimeoutExpired('Command `{}` timed out'.format(cmd))
        timer.cancel() 
Example 9
Project: genmon   Author: jgyates   File: genexercise.py    License: GNU General Public License v2.0 6 votes vote down vote up
def PostWarmup(self):

        # check to see if the generator is running
        status = self.SendCommand("generator: getbase")
        if not status.lower() in ["running", "exercising"]:
            self.LogError("WARNING: generator not running post warmup. Transfer switch not activated.")
            self.SendCommand("generator: setremote=stop")
            return

        self.SendCommand("generator: setremote=starttransfer")
        self.DebugOutput("Starting transfer exercise cycle (post warmup).")
        # set timer to stop
        self.StopTimer = threading.Timer(float(self.ExerciseDuration  * 60.0), self.StopExercise)
        self.StopTimer.start()

    # ---------- GenExercise::ReadyToExercise----------------------------------- 
Example 10
Project: vscode-esp-idf-extension   Author: espressif   File: debug_adapter.py    License: Apache License 2.0 6 votes vote down vote up
def poll_target(self, *kwargs):
        log.info("Poll target")
        if self.state.wait_target_state == dbg.TARGET_STATE_STOPPED:
            stopped,rsn_str = self.is_stopped()
            if stopped:
                self.state.wait_target_state = dbg.TARGET_STATE_UNKNOWN
                self.__command_processor.generate_StoppedEvent(reason=rsn_str,
                                                               thread_id=0,
                                                               all_threads_stopped=True)
        elif self.state.wait_target_state == dbg.TARGET_STATE_RUNNING:
            # this is not fully implemented yet, need to define when we need to start waiting for target get running
            try:
                self._gdb.wait_target_state(dbg.TARGET_STATE_RUNNING, 0)
                self.state.wait_target_state = dbg.TARGET_STATE_UNKNOWN
                self.__command_processor.generate_ContinuedEvent(thread_id=0,
                                                                all_threads_continued=True)
            except dbg.DebuggerTargetStateTimeoutError:
                pass
        if self.state.wait_target_state != dbg.TARGET_STATE_UNKNOWN:
            # restart timer if we still need to wait for target state
            self.target_poller = threading.Timer(1.0, self.poll_target, args=[self,])
            self.target_poller.start() 
Example 11
Project: Faraday-Software   Author: FaradayRF   File: layer_2_protocol.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, input_channel, serial_physical_obj):
        #Initialize class variables
        self.rx_packet_queue = Queue.Queue()
        self.rx_data_payload_queue = Queue.Queue()
        self.logic_startbyte_received = False
        self.logic_escapebyte_received = False
        self.logic_stopbyte_received = False
        self.receiver_class = Receiver_Datalink_Device_State_Parser_Class(input_channel, serial_physical_obj)
        self.enable_flag = True
        self.max_payload_size = 6
        self.datalink_packet_format = 'c' + str(self.max_payload_size) + 'c' + 'c'
        self.reconstruct_data = ''
        self.timer_interval = 5
        self.timer = threading.Timer(self.timer_interval, self.timer_trip)
        self.datalink_packet_struct = struct.Struct('BBB125s')

        #Start
        threading.Thread.__init__(self)
        self.start()  #Starts the run() function and thread 
Example 12
Project: rainbow-hat   Author: pimoroni   File: buzzer.py    License: MIT License 6 votes vote down vote up
def note(frequency, duration=1.0):
    """Play a single note.

    :param frequency: Musical frequency in hertz
    :param duration: Optional duration in seconds, use None to sustain note

    """
    global _timeout

    setup()

    if frequency <= 0:
        raise ValueError("Frequency must be > 0")

    if duration is not None and duration <= 0:
        raise ValueError("Duration must be > 0")

    clear_timeout()

    pwm.ChangeFrequency(frequency)
    GPIO.setup(BUZZER, GPIO.OUT)

    if duration is not None and duration > 0:
        _timeout = Timer(duration, stop)
        _timeout.start() 
Example 13
Project: apt2   Author: tatanus   File: utils.py    License: MIT License 6 votes vote down vote up
def execWait(cmd, outfile=None, timeout=0):
        result = ""
        env = os.environ
        proc = subprocess.Popen(cmd, executable='/bin/bash', env=env, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)

        if timeout:
            timer = threading.Timer(timeout, proc.kill)
            timer.start()
        result = proc.communicate()[0]
        if timeout:
            if timer.is_alive():
                timer.cancel()
        if outfile:
            if Utils.fileExists(outfile):
                print "FILE ALREADY EXISTS!!!!"
            else:
                tmp_result = "\033[0;33m(" + time.strftime(
                    "%Y.%m.%d-%H.%M.%S") + ") <pentest> #\033[0m " + cmd + Utils.newLine() + Utils.newLine() + result
                Utils.writeFile(tmp_result, outfile)
        return result 
Example 14
Project: openplotter   Author: sailoog   File: read_sensors_d.py    License: GNU General Public License v2.0 6 votes vote down vote up
def work_analog():
	threading.Timer(rate_ana, work_analog).start()
	SignalK='{"updates":[{"$source":"OPsensors.SPI.MCP3008","values":[ '
	Erg=''
	send=False
	for i in MCP:
		if i[0]==1:
			send=True
			XValue=read_adc(i[1])
			if i[4]==1:
				XValue = interpolread(i[1],XValue)
			Erg +='{"path": "'+i[2]+'","value":'+str(XValue)+'},'

	if send:
		SignalK +=Erg[0:-1]+']}]}\n'
		sock.sendto(SignalK, ('127.0.0.1', 55557))	
	
# read gpio and GENERATE SK 
Example 15
Project: ironpython2   Author: IronLanguages   File: excelRTDServer.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 16
Project: picochess   Author: jromang   File: timecontrol.py    License: GNU General Public License v3.0 6 votes vote down vote up
def start_internal(self, color, log=True):
        """Start the internal clock."""
        if not self.internal_running():
            if self.mode in (TimeMode.BLITZ, TimeMode.FISCHER):
                self.active_color = color
                self.reset_start_time()

            if log:
                w_hms, b_hms = self._log_time()
                logging.info('start internal time w:%s - b:%s [ign]', w_hms, b_hms)
                logging.info('received clock time w:%s - b:%s [use]',
                             hms_time(self.clock_time[chess.WHITE]), hms_time(self.clock_time[chess.BLACK]))

            self.internal_time[chess.WHITE] = self.clock_time[chess.WHITE]
            self.internal_time[chess.BLACK] = self.clock_time[chess.BLACK]

            # Only start thread if not already started for same color, and the player has not already lost on time
            if self.internal_time[color] > 0 and self.active_color is not None and self.run_color != self.active_color:
                self.timer = threading.Timer(copy.copy(self.internal_time[color]), self._out_of_time,
                                             [copy.copy(self.internal_time[color])])
                self.timer.start()
                logging.debug('internal timer started - color: %s run: %s active: %s',
                              color, self.run_color, self.active_color)
                self.run_color = self.active_color 
Example 17
Project: hydrus   Author: HTTP-APIs   File: stale_records_cleanup.py    License: MIT License 5 votes vote down vote up
def remove_stale_modification_records(session: scoped_session,
                                      stale_records_removal_interval: int=900):
    """
    Remove modification records which are older than last 1000 records.
    :param session: sqlalchemy session.
    :param stale_records_removal_interval: Interval time to run the removal job.
    """
    timer = Timer(stale_records_removal_interval,
                  remove_stale_modification_records, [session])
    timer.daemon = True
    timer.start()
    # Get all valid records.
    valid_records = session.query(Modification).order_by(
        Modification.job_id.desc()).limit(1000).all()
    # If number of returned valid records is less than set limit then
    # there is nothing to clean up.
    if len(valid_records) < 1000:
        return
    else:
        # Get the job_id of last (oldest) valid record.
        job_id_of_last_valid_record = valid_records[-1].job_id
        # Get all records which are older than the oldest valid record.
        stale_records = session.query(Modification).filter(
            Modification.job_id < job_id_of_last_valid_record).all()
        for record in stale_records:
            session.delete(record)
        session.commit()
    session.remove() 
Example 18
Project: BASS   Author: Cisco-Talos   File: ida_service.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_call(cmd, cwd = os.getcwd(), timeout = None, env = os.environ):
    proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = env, cwd = cwd)
    if timeout:
        timer = Timer(timeout, proc.kill)
        timer.start()
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise OSError(proc.returncode, "Subprocess returned error code") 
Example 19
Project: BASS   Author: Cisco-Talos   File: ida_service.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_call(cmd, cwd = os.getcwd(), timeout = None, env = os.environ):
    proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = env, cwd = cwd)
    if timeout:
        timer = Timer(timeout, proc.kill)
        timer.start()
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise OSError(proc.returncode, "Subprocess returned error code") 
Example 20
Project: RF-Monitor   Author: EarToEarOak   File: cli.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __restart_gps(self):
        timer = Timer(GPS_RETRY, self.__start_gps)
        timer.start() 
Example 21
Project: LPHK   Author: nimaid   File: lp_events.py    License: GNU General Public License v3.0 5 votes vote down vote up
def init(lp_object):
    global timer
    global press_funcs
    timer = threading.Timer(RUN_DELAY, run, (lp_object,)) 
Example 22
Project: LPHK   Author: nimaid   File: scripts.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_kill(x, y, is_async, killfunc=None):
    coords = "(" + str(x) + ", " + str(y) + ")"
    
    if threads[x][y].kill.is_set():
        print("[scripts] " + coords + " Recieved exit flag, script exiting...")
        threads[x][y].kill.clear()
        if not is_async:
            running = False
        if killfunc:
            killfunc()
        threading.Timer(EXIT_UPDATE_DELAY, lp_colors.updateXY, (x, y)).start()
        return True
    else:
        return False 
Example 23
Project: knob   Author: francozappa   File: cmds.py    License: MIT License 5 votes vote down vote up
def _spawnWireshark(self):
                # Global Header Values
                PCAP_GLOBAL_HEADER_FMT = '@ I H H i I I I '
                PCAP_MAGICAL_NUMBER = 2712847316
                PCAP_MJ_VERN_NUMBER = 2
                PCAP_MI_VERN_NUMBER = 4
                PCAP_LOCAL_CORECTIN = 0
                PCAP_ACCUR_TIMSTAMP = 0
                PCAP_MAX_LENGTH_CAP = 65535
                PCAP_DATA_LINK_TYPE = self.pcap_data_link_type

                pcap_header = struct.pack('@ I H H i I I I ',
                        PCAP_MAGICAL_NUMBER,
                        PCAP_MJ_VERN_NUMBER,
                        PCAP_MI_VERN_NUMBER,
                        PCAP_LOCAL_CORECTIN,
                        PCAP_ACCUR_TIMSTAMP,
                        PCAP_MAX_LENGTH_CAP,
                        PCAP_DATA_LINK_TYPE)

                self.wireshark_process = subprocess.Popen(
                        ["wireshark", "-k", "-i", "-"], 
                        stdin=subprocess.PIPE)

                self.wireshark_process.stdin.write(pcap_header)

                self.poll_timer = Timer(3, self._pollTimer, ())
                self.poll_timer.start() 
Example 24
Project: knob   Author: francozappa   File: cmds.py    License: MIT License 5 votes vote down vote up
def _pollTimer(self):
                if self.running and self.wireshark_process != None:
                    if self.wireshark_process.poll() == 0:
                        # Process has ended
                        log.debug("_pollTimer: Wireshark has terminated")
                        self.stopMonitor()
                        self.wireshark_process = None
                    else:
                        # schedule new timer
                        self.poll_timer = Timer(3, self._pollTimer, ())
                        self.poll_timer.start() 
Example 25
Project: python-lifx-sdk   Author: smarthall   File: util.py    License: MIT License 5 votes vote down vote up
def run(self):
        while self.event.is_set():
            t = threading.Timer(self.interval, self.callable,
                                self.args, self.kwargs)
            t.start()
            t.join() 
Example 26
Project: aws-ops-automator   Author: awslabs   File: timer.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, timeout_seconds, start=True):
        self.timeout = False
        self._timer = threading.Timer(interval=timeout_seconds, function=self.fn)
        if timeout_seconds > 0 and start:
            self.start() 
Example 27
Project: aws-ops-automator   Author: awslabs   File: custom_resource.py    License: Apache License 2.0 5 votes vote down vote up
def handle_request(self):
        """
        Handles cloudformation custom resource request
        :return: response that is send back containing the result
        """
        timer = None
        if self._context is not None:
            time_left = (self._context.get_remaining_time_in_millis() / 1000.00) - 0.5 if self._context is not None else 300
            if self.timeout is not None:
                time_left = min(time_left, float(self.timeout))
            timer = threading.Timer(time_left, self.fn_timeout)
            timer.start()

        try:
            # Call handler for request type
            if self.request_type == CustomResource.EVENT_TYPE_CREATE:
                result = self._create_request()
            elif self.request_type == CustomResource.EVENT_TYPE_UPDATE:
                result = self._update_request()
            elif self.request_type == CustomResource.EVENT_TYPE_DELETE:
                result = self._delete_request()
            else:
                raise ValueError("\"{}\" is not a valid request type".format(self.request_type))

            # Set status based on return value of handler
            self.response["Status"] = "SUCCESS" if result else "FAILED"

            # set physical resource id or create new one
            self.response["PhysicalResourceId"] = self.physical_resource_id or self.new_physical_resource_id()

        except Exception as ex:
            self.response["Status"] = "FAILED"
            self.response["Reason"] = str(ex)

        if timer is not None:
            timer.cancel()

        return self._send_response() 
Example 28
Project: aws-ops-automator   Author: awslabs   File: select_resources_handler.py    License: Apache License 2.0 5 votes vote down vote up
def start_timer(self, remaining):
        execution_time_left = (self._context.get_remaining_time_in_millis() / 1000.00) - remaining
        self._timer = threading.Timer(execution_time_left, self.select_timed_out)
        self._timer.start() 
Example 29
Project: fitbit-googlefit   Author: praveendath92   File: auth_fitbit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def browser_authorize(self):
        """
        Open a browser to the authorization url and spool up a CherryPy
        server to accept the response
        """
        url, _ = self.oauth.authorize_token_url(redirect_uri=self.redirect_uri)
        # Open the web browser in a new thread for command-line browser support
        threading.Timer(1, webbrowser.open, args=(url,)).start()
        cherrypy.quickstart(self) 
Example 30
Project: fitbit-googlefit   Author: praveendath92   File: auth_fitbit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _shutdown_cherrypy(self):
        """ Shutdown cherrypy in one second, if it's running """
        if cherrypy.engine.state == cherrypy.engine.states.STARTED:
            threading.Timer(1, cherrypy.engine.exit).start()