def main(): logger.debug("---------------------------------------------------------------------------------") logger.debug("------------------------Welcome to Virtlet Daemon.-------------------------------") logger.debug("------Copyright (2019, ) Institute of Software, Chinese Academy of Sciences------") logger.debug("---------author: [email protected], [email protected]") logger.debug("------------------------------liuhe18@otcaix.iscas.ac.cn-------------------------") logger.debug("---------------------------------------------------------------------------------") if os.path.exists(TOKEN): config.load_kube_config(config_file=TOKEN) try: thread_1 = Thread(target=libvirt_event_handler) thread_1.daemon = True thread_1.name = 'libvirt_event_handler' thread_1.start() thread_2 = Thread(target=os_event_handler) thread_2.daemon = True thread_2.name = 'os_event_handler' thread_2.start() # if not is_kubernetes_master(): thread_3 = Thread(target=host_cycler) thread_3.daemon = True thread_3.name = 'host_cycler' thread_3.start() try: while True: time.sleep(1) except KeyboardInterrupt: return thread_1.join() thread_2.join() # if not is_kubernetes_master(): thread_3.join() except: logger.error('Oops! ', exc_info=1)
def consultar_todas_as_plataformas(self, paralelo = False): repository = CotacoesRepository() plataformas = repository.listar_plataformas() lista_threads = list() #Usado apenas para execução paralela print("Consultando plataforma") for p in plataformas: print("Contultando plataforma "+p.nome) if (p.ultimo + self.LIMITE_PARA_USO_DA_ROTINA_PARA_COTACOES_RECENTES)<datetime.now(): if paralelo: crawler = CrawlerPlataformas() crawler.plataforma = p t = Thread(target=crawler.consultar_dados_antigos, daemon=True) t.name = "Consultar_dados_antigos" lista_threads.append(t) t.start() else: self.plataforma = p self.consultar_dados_antigos() else: if paralelo: crawler = CrawlerPlataformas() crawler.plataforma = p t = Thread(target=crawler.consultar_dados_recentes, daemon=True) t.name = "Consultar_dados_recentes" lista_threads.append(t) t.start() else: self.plataforma = p self.consultar_dados_recentes()
def start_node(): init_blockchain() server.start_server() # Pending agent pending_agent_thread = Thread(target=pending_block_agent) pending_agent_thread.daemon = True pending_agent_thread.name = "Pending block Agent" pending_agent_thread.start() # Open Transaction agent open_trans_agent_thread = Thread(target=open_transactions_agent) open_trans_agent_thread.daemon = True open_trans_agent_thread.name = "Open Transaction Agent" open_trans_agent_thread.start() # Remove Old agent remove_agent_agent_thread = Thread(target=remove_old.agent) remove_agent_agent_thread.daemon = True remove_agent_agent_thread.name = "Remove Old Agent" remove_agent_agent_thread.start() # Sync chain agent sync_chain_agent_thread = Thread(target=sync_blockchain_agent) sync_chain_agent_thread.daemon = True sync_chain_agent_thread.name = "Sync Blockchain Agent" sync_chain_agent_thread.start()
def startThreads(): for i in range(onStatusNumWorkerThreads): t = Thread(target=statusWorker) t.name = "Status%d" % i t.start() threads.append(t) for i in range(onStateNumWorkerThreads): t = Thread(target=stateWorker) t.name = "State%d" % i t.start() threads.append(t) for i in range(onToogleNumWorkerThreads): t = Thread(target=toogleWorker) t.name = "Toogle%d" % i t.start() threads.append(t) for i in range(onValueNumWorkerThreads): t = Thread(target=valueWorker) t.name = "Value%d" % i t.start() threads.append(t) for i in range(onDeviceDataNumWorkerThreads): t = Thread(target=deviceDataWorker) t.name = "DeviceData%d" % i t.start() threads.append(t)
def main(): # Initialize webcam webcam = cv2.VideoCapture(0) # Start GazeTracking gaze = GazeTracking() thread_gaze = Thread(target=gaze.run, args=(webcam, )) thread_gaze.name = "ThreadGaze" #thread_gaze.daemon = True thread_gaze.start() # Calibrate size = pyautogui.size() # changed manually to test only in my primary monitor size = (1920, 1080) calibration = Calibration(gaze, size) # Show annotated camera annotated_frame = AnnotatedFrame(gaze) thread_annotated = Thread(target=annotated_frame.show) thread_annotated.name = "ThreadAnnotated" #thread_annotated.daemon = True thread_annotated.start() # Initialize mouse control mouse_control = MouseControl(gaze, calibration) mouse_control.run()
def main(argv): global stop global start global counting # --- Broker # broker_ip = 'ec2-54-208-177-151.compute-1.amazonaws.com' broker_ip = 'localhost' broker_queue = 'test' sub_thread = Thread(target=createSubMaster, args=(broker_ip, 'master')) sub_thread.name = 'SubMasterThread' sub_thread.daemon = True sub_thread.start() sub_thread = Thread(target=createSub, args=(broker_ip, broker_queue)) sub_thread.name = 'SubThread' sub_thread.daemon = True sub_thread.start() # --- Time to set up all clients time.sleep(5) print("Waiting for command to start..") while start == False: time.sleep(0.1) # --- Time to set up all clients print("Warming up... (" + str(WARMUP_DURATION) + "s)") time.sleep(WARMUP_DURATION) print("Starting...") counting = True with open("sv_p" + str(PUBLISHERS) + "t" + str(THROUGHPUT) + ".csv", 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) start_time = time.time() i = 1 while stop == False: print(i, message_counter) time_now = str(time.time() - start_time) cpu = str(psutil.cpu_percent()) memory = str(psutil.virtual_memory().percent) spamwriter.writerow([i + 1, time_now, cpu, memory]) i = i + 1 time.sleep(ITERATION_DURATION) print("Stopping server...") print("Total of messages received: " + str(message_counter))
def main(): # Add one Node statics.NODES.append(f"http://{NODE_ADDRESS}:{NODE_PORT}") # Start node manager node_manager_thread = Thread(target=node_manager) node_manager_thread.daemon = True node_manager_thread.name = "Node Manager Thread" node_manager_thread.start() # Start user Interface if args.lite is False: statics.LITE_ACTIVE = False user_thread = Thread(target=user_interface) user_thread.daemon = True user_thread.name = "User Interface" user_thread.start() statics.RUNNING_PROCESSES.append(user_thread) print("[INFO] User interface is available") if args.node: # Start node node_thread = Thread(target=node.start_node) node_thread.daemon = True node_thread.name = "Node Thread" node_thread.start() statics.RUNNING_PROCESSES.append(node_thread) if args.miner: # Start miner miner_thread = Thread(target=mining.start_miner) miner_thread.daemon = True miner_thread.name = "Miner Thread" miner_thread.start() statics.RUNNING_PROCESSES.append(miner_thread) if args.api: # Start API flask_server.start_api() print("[INFO] Every task is running") # Wait to complete or close statement gived while len(statics.RUNNING_PROCESSES) > 0 and statics.CLOSING is False: try: for process in statics.RUNNING_PROCESSES: # Remove dead threads if process.is_alive() is False: statics.RUNNING_PROCESSES.remove(process) time.sleep(0.25) except (KeyboardInterrupt, EOFError): print("Keyboard Interrupt detected") break print("[INFO] Closing everything...") statics.CLOSING = True
def go(self): self.connect() send_loop = Thread(daemon=True, target=self.send_loop) send_loop.name = "tutkain.client.send_loop" send_loop.start() recv_loop = Thread(daemon=True, target=self.recv_loop) recv_loop.name = "tutkain.client.recv_loop" recv_loop.start() return self
def main(): # Init config.init_server() hive.LatestPostManager() reset_analytics() # Start counter thread post_count_thread = Thread(target=database.latest_post_count_manager) post_count_thread.name = "Get latest_posts count" post_count_thread.daemon = True post_count_thread.start() # Start task manager thread task_manager_thread = Thread(target=task_manager) task_manager_thread.name = "Taskmanager" task_manager_thread.daemon = True task_manager_thread.start() # Start remove Profiler thread remove_old_profiler_thread = Thread(target=Profiler.remove_old_profiler) remove_old_profiler_thread.name = "Remove old Profiler" remove_old_profiler_thread.daemon = True #remove_old_profiler_thread.start() # Wait until something happens while True: try: _input = input() if 'exit' in _input or 'break' in _input or 'quit' in _input: # Stop break if 'tasks' in _input: # Get all tasks print(f"Tasks({len(config.statics.task_list)}) are running: ") for name, timestamp, _, _ in config.statics.task_list: print(f"{name} from {timestamp}") if 'profiler' in _input: # Profile one --> Add task username = _input.split(' ')[1] #profiler christopher2002 database.commit_query("INSERT INTO tasks(name, timestamp, parameter_one, parameter_two) VALUES (%s, %s, %s, %s);", ("profiler", datetime.utcnow().strftime("%d.%m.%YT%H:%M:%S"), username, "")) print("Created profiling task for " + username) except KeyboardInterrupt: break
def init_and_work(cls, mainFunction, event_handler = None): """ Inicia las estructuras para hacer el trabajo. Se crea un hilo secundario que ejecuta el MainFunction con la función del usuario mientras que el hilo principal ejecuta una aplicación Qt. Se usa event_handler para sobreescribir el manejo de eventos globales en el la función del hilo secundario (excepciones y en caso de salida) """ def work(mainFunction, event_handler): "La función del hilo secundario" res = 1 try: res = mainFunction() except Exception as ex: # Maneja las excepciones no manejadas res = event_handler.handle_error(ex) finally: event_handler.on_end(res) if event_handler == None: event_handler = _DefaultHandler() # setea el manejador de SIGINT signal.signal(signal.SIGINT, signal.SIG_DFL) # llama al hilo para empezar a correr worker = Thread(target = work, args = (mainFunction, event_handler)) worker.name = "UserMainThread" worker.start() cls.__wait_for_framework_init()
def processKeys(): thread = None killEvent = Event() lastFlush = time.time() kq = keyQueue() thread = Thread(target=keyReader,args=(stdscr,kq,killEvent)) thread.name = 'keyboard-reader' thread.start() while(True): try: while (kq.size() == 0): time.sleep(0.1) now = time.time() #queue up keys for 1 second before sending off since there #is a lot of latency sending events across adb if ((now - lastFlush) > 1): while(kq.size() > 0): #get the next block of keys of the same type (special or not) isSpecial,vals = kq.getValsBlock() if (isSpecial): AdbUtils.adbSendSpecials(vals) else: AdbUtils.adbSendKeys(vals) stdscr.refresh() lastFlush = time.time() except KeyboardInterrupt: break killEvent.set()
def manager(rest_url = 'statuses/user_timeline'): # print("manager: waiting tasks...") # while tq.empty(): # time.sleep(1) print("manager: start looping all keys, will quit when the main thread quit.") while 1: with open('./twitter_api_keys.pydict','r') as f: api_keys = dict((key['consumer_key'], key) for key in eval(f.read())) n = 0 for i, consumer_key in enumerate(api_keys): time.sleep(1) current_workers = list(t.name for t in enumerate_threads() if "Thread" not in t.name) if consumer_key in current_workers or tq.qsize() < len(current_workers): continue worker = Thread(target = crawler, kwargs ={'key': api_keys[consumer_key], 'name': '{min}:{max}-{no:>25}'.format(min = min(RG), max = max(RG), no = consumer_key), 'rest_url':rest_url}) worker.daemon = True worker.name = consumer_key worker.start() n = n + 1 # print(("manager: {} workers are working.".format(len(current_workers)))) # if n>0: print(("manager: {} new workers are dispatched.".format(n))) print("manager: quit.")
def __init__(self, nthreads): """ Inicializa el pipeline. Puede procesar hasta <nthreads> en paralelo """ if nthreads < 1: raise ValueError("nthreads must be at least 1") # Variables de sincronización self.lock = Lock() self.__events_queue = deque() self.__events_queue_non_empty = Condition() self.__items_queue = deque() self.__finished = Condition() # los hilos que están corriendo un item están en False, los otros están # en True self.__worker_threads = { # libres True: set([ _PipelineWorkerThread(i+1, self) for i in range(nthreads) ]), # corriendo un item False : set([]) } # Inicia el hilo de control de pipeline worker = Thread(target = ItemProcesorPipeline.__controller_thread_func, args = (self, ) ) worker.name = "ItemProcesorPipeline-Main" worker.daemon = True worker.start()
def BatchFileTrans(self, fileList=list): """ 批量转义列表文件,转义并处理进度条 :param fileList: 批量转义的文件列表 :return: """ try: dstPath = C3ATOTransferDlg.CheckAndCreateTransDir(self.oldBatchDir) # 创建镜像的转义文件路径 except Exception as err: print(err) self.textC3ATOProcess.append('Info:'+'文件遍历!') self.barAllAdd = C3ATOTransferDlg.ComputeEBarAllAdd(fileList) # 创建线程池 thList = [] # 对于多文件选择,在当前目录直接完成 for recordFile in fileList: # 按照之前创建目录规则,创建新的文件名 transFile = recordFile.replace(self.oldBatchDir, dstPath) # 先替换镜像顶级目录内容 dstFile = transFile.replace('.txt', '_trans.txt') # 计算转换后的文件名称,只有文件发生变化 # 对每个转换文件过程创建线程 t = Thread(target=self.translator.TransContent, args=(recordFile, dstFile)) # 添加内容 t.name = '线程' + dstFile thList.append(t) # 开启线程 threadAct = Thread(target=self.ThreadManage, args=(thList,)) # 添加内容 threadAct.start()
def run(self, host, port): window = self.window try: client = Client(host, int(port)).go() plugin_session = client.clone_session() sessions.register(window.id(), 'plugin', plugin_session) user_session = client.clone_session() sessions.register(window.id(), 'user', user_session) # Create an output panel for printing evaluation results and show # it. self.configure_output_panel() # Start a worker thread that reads items from a queue and prints # them into an output panel. print_loop = Thread(daemon=True, target=self.print_loop, args=(client.recvq, )) print_loop.name = 'tutkain.print_loop' print_loop.start() plugin_session.output( {'out': 'Connected to {}:{}.\n'.format(host, port)}) plugin_session.client.sendq.put({'op': 'describe'}) except ConnectionRefusedError: window.status_message('ERR: connection to {}:{} refused.'.format( host, port))
def run_local_command(args): """ Executes the formatted command. :param args: Command-Line arguments. :type args: list|tuple :returns: The Process created by Popen instance and The Output Queue :rtype: subprocess.Popen, Queue.Queue() """ env = os.environ.copy() process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, close_fds=ON_POSIX, env=env) queue = Queue.Queue() t = Thread(target=enqueue_output, args=(process.stdout, queue)) t.name = "Thread exec: {0}".format(args) t.daemon = True # thread dies with the program t.start() return process, queue
def start_locator_thread(args): search_thread = Thread(target=search_loop, args=(args,)) search_thread.daemon = True search_thread.name = 'search_thread' search_thread.start() return search_thread
def start_daemon_thread(target, name): from threading import Thread t = Thread(target=target) t.name = name t.daemon = True t.start() return t
def __init__(self, dl, v, d, o, b, k): """ Initialises demuxer class """ # Configure instance globals self.rxq = deque() # Data receive queue self.coreReady = False # Core thread ready state self.coreStop = False # Core thread stop flag self.downlink = dl # Downlink type (LRIT/HRIT) self.verbose = v # Verbose output flag self.dumpPath = d # VCDU dump file path self.outputPath = o # Output path root self.blacklist = b # VCID blacklist self.keys = k # Decryption keys self.channelHandlers = {} # List of channel handlers if self.downlink == "LRIT": self.coreWait = 54 # Core loop delay in ms for LRIT (108.8ms per packet @ 64 kbps) elif self.downlink == "HRIT": self.coreWait = 1 # Core loop delay in ms for HRIT (2.2ms per packet @ 3 Mbps) # Start core demuxer thread demux_thread = Thread() demux_thread.name = "DEMUX CORE" demux_thread.run = self.demux_core demux_thread.start()
def main(): logger.debug( "---------------------------------------------------------------------------------" ) logger.debug( "------------------------Welcome to Virtlet Daemon.-------------------------------" ) logger.debug( "------Copyright (2019, ) Institute of Software, Chinese Academy of Sciences------" ) logger.debug( "---------author: [email protected],[email protected]" ) logger.debug( "--------------------------------wuheng@otcaix.iscas.ac.cn------------------------" ) logger.debug( "---------------------------------------------------------------------------------" ) logger.debug("Loading kube token in 'default.cfg' ...") try: thread_1 = Thread(target=write_token_to_file) thread_1.daemon = True thread_1.name = 'write_token_to_file' thread_1.start() try: while True: time.sleep(3) except KeyboardInterrupt: return except: logger.error('Oops! ', exc_info=1)
def predict_video(): try: item_id = request.json['id'] item = videos.find_one({'_id': item_id}) job_is_running = False for thread in threading.enumerate(): if thread.name == 'fish_loc_predict': job_is_running = True if not job_is_running: thread = Thread(target=trainval, args=( checkUploadCanceled, onProgressUpload, onFishCounted, item_id, item['original_video_path'], item['predicted_video_path'] )) thread.name = 'fish_loc_predict' thread.daemon = True thread.start() else: raise Exception('Currenty only one thread can be used for Prediction') except Exception as e: return make_response(str(e), 400) return make_response(jsonify({}), 204)
def start(self, task_name, **kwargs): """Start a given task in a new daemon thread, and return the thread. kwargs are passed to :py:meth:`task.run() <earwigbot.tasks.Task.run>`. If the task is not found, ``None`` will be returned and an error will be logged. """ msg = "Starting task '{0}' in a new thread" self.logger.info(msg.format(task_name)) try: task = self.get(task_name) except KeyError: e = "Couldn't find task '{0}'" self.logger.error(e.format(task_name)) return task_thread = Thread(target=self._wrapper, args=(task, ), kwargs=kwargs) start_time = strftime("%b %d %H:%M:%S") task_thread.name = "{0} ({1})".format(task_name, start_time) task_thread.daemon = True task_thread.start() return task_thread
def __start_server(self): while True: socket_client, client_address = self.__socket_server.accept() if socket_client not in self.client_list: self.client_list.append(socket_client) while len(self.client_list) != len(self.pid_list): sleep(1) self.__pid2client[self.pid_list[-1]] = socket_client self.logger.info( f"A WeChat process successfully connected (PID:{self.pid_list[-1]})" ) if self.__key: request = spy_pb2.Request() request.cmd = 9527 request.key = self.__key request.uuid = "" request.sync = 0 data = request.SerializeToString() data_length_bytes = int.to_bytes(len(data), length=4, byteorder="little") socket_client.send(data_length_bytes + data) t_socket_client_receive = Thread(target=self.receive, args=(socket_client, )) t_socket_client_receive.name = f"client {client_address[1]}" t_socket_client_receive.daemon = True t_socket_client_receive.start()
def start_locator_thread(args): api = PGoApi() args.api = api search_thread = Thread(target=search_loop, args=(args,)) search_thread.daemon = True search_thread.name = 'search_thread' search_thread.start()
def add_thread(self, name, code, *args, **kwargs): """adds a thread to thread_list and starts it if none are running""" thread = Thread(target=self.thread_run, args=(code,)+args, kwargs=kwargs)#, args=(self.loop_step, 10)) thread.name=name self.thread_list.append(thread) if self.thread is None: self.start_thread()
def main(): threads = [] t = Thread(target=initTerm, args=(ctrlQueue,respQueue)) t.name = "User Command Loop" threads.append(t) t.start()
def __init__(self, parser=None, error_handle=None, download_image=False, multi=False): self.logger = logging.getLogger() self.logger.addHandler(sh) self.logger.setLevel(logging.DEBUG) # 是否下载图片(小于2MB) # 该参数为True时 微信会自动下载收到的小于2MB的图片 但会造成图片消息延迟响应 self.__download_image = download_image # TODO: 异常处理函数 self.__error_handle = error_handle # 是否多开微信PC客户端 self.__multi = multi # socket数据处理函数 self.__parser = parser self.__socket_client_dict = {} self.__socket_server = socket(AF_INET, SOCK_STREAM) self.__socket_server.bind(("127.0.0.1", 9527)) self.__socket_server.listen(1) t_start_server = Thread(target=self.__start_server) t_start_server.daemon = True t_start_server.name = "socket accept" t_start_server.start()
def start_thread(target, name, *args): """Launch thread.""" t = Thread(target=target, args=args) t.name = name t.daemon = True t.start() return t
def rerequest(self, s, callback, params): proxy_mode = self.config.get('proxy_mode', 0) if proxy_mode == PROXY_MODE_PRIVATE: if DEBUG: log(self.log_prefix + 'PROXY_MODE_PRIVATE, rerequest exited') return if DEBUG_ANNOUNCE: print_stack() if not self.lock.isready(): def retry(self=self, s=s, callback=callback, params=params): self.rerequest(s, callback, params) self.sched(retry, 5) if DEBUG_LOCK or DEBUG_ANNOUNCE: log( self.log_prefix + 'rerequest: locked, retry in 5 seconds: s', s, 'callback', callback, 'params', params, 'thread', currentThread().name) return rq = Thread(target=self._rerequest, args=[s, callback, params]) rq.name = 'TrackerRerequestA' + rq.name rq.daemon = True if DEBUG_LOCK or DEBUG_ANNOUNCE: log(self.log_prefix + 'rerequest: start new request: s', s, 'thread', rq.name) rq.start()
def rerequest_single(self, t, s, params): l = self.lock.set() if t.startswith('udp'): target = self._rerequest_single_udp args = [t, params, l] else: target = self._rerequest_single args = [t, s + get_key(t), l] rq = Thread(target=target, args=args) rq.name = 'TrackerRerequestB' + rq.name rq.daemon = True if DEBUG_LOCK or DEBUG_ANNOUNCE: log(self.log_prefix + 'rerequest_single: start new thread: t', t, 'set_lock', l, 'thread', rq.name) rq.start() if DEBUG_LOCK: log(self.log_prefix + 'rerequest_single: wait for lock: thread', currentThread().name) self.lock.wait() if DEBUG_LOCK or DEBUG_ANNOUNCE: log( self.log_prefix + 'rerequest_single: wait for lock done: success', self.lock.success, 'thread', currentThread().name) if self.lock.success: self.lastsuccessful = t self.last_failed = False self.never_succeeded = False return True if not self.last_failed and self.lastsuccessful == t: self.last_failed = True self.lock.give_up() return True return False
def run(self, output_fn, **kwargs): logger.debug( "---------------------------------------------------------------------------------" ) logger.debug( "------------------------Welcome to Virtlet Daemon.-------------------------------" ) logger.debug( "------Copyright (2019, ) Institute of Software, Chinese Academy of Sciences------" ) logger.debug( "---------author: [email protected],[email protected]" ) logger.debug( "--------------------------------wuheng@otcaix.iscas.ac.cn------------------------" ) logger.debug( "---------------------------------------------------------------------------------" ) config.load_kube_config(config_file=TOKEN) try: thread_1 = Thread(target=vnc_token_loop) thread_1.daemon = True thread_1.name = 'vnc_token_loop' thread_1.start() try: while True: time.sleep(1) except KeyboardInterrupt: return except: logger.error('Oops! ', exc_info=1)
def init_check_network_connection(self): t = Thread(target=self.check_network_connection, args=[False, 5, True]) t.name = 'RerequestCheckNetwork' + t.name t.daemon = True if DEBUG_LOCK or DEBUG_ANNOUNCE: log(self.log_prefix + 'init_check_network_connection: start check_network_connection(): thread', t.name) t.start()
def rerequest_single(self, t, s, params): l = self.lock.set() if t.startswith('udp'): target = self._rerequest_single_udp args = [t, params, l] else: target = self._rerequest_single args = [t, s + get_key(t), l] rq = Thread(target=target, args=args) rq.name = 'TrackerRerequestB' + rq.name rq.daemon = True if DEBUG_LOCK or DEBUG_ANNOUNCE: log(self.log_prefix + 'rerequest_single: start new thread: t', t, 'set_lock', l, 'thread', rq.name) rq.start() if DEBUG_LOCK: log(self.log_prefix + 'rerequest_single: wait for lock: thread', currentThread().name) self.lock.wait() if DEBUG_LOCK or DEBUG_ANNOUNCE: log(self.log_prefix + 'rerequest_single: wait for lock done: success', self.lock.success, 'thread', currentThread().name) if self.lock.success: self.lastsuccessful = t self.last_failed = False self.never_succeeded = False return True if not self.last_failed and self.lastsuccessful == t: self.last_failed = True self.lock.give_up() return True return False
def start_async_loop(name): loop = asyncio.new_event_loop() t = Thread(target=async_loop_thread, args=(loop, )) t.name = "{} [async loop]".format(name) t.daemon = True t.start() return loop
def __init__(self, config): """ Initialises demuxer class """ # Configure instance globals self.config = config # Configuration tuple self.rxq = deque() # Data receive queue self.coreReady = False # Core thread ready state self.coreStop = False # Core thread stop flag self.channels = {} # List of channel handlers self.currentVCID = None # Current Virtual Channel ID self.lastImage = None # Last image output by demuxer self.lastXRIT = None # Last xRIT file output by demuxer if self.config.downlink == "LRIT": self.coreWait = 54 # Core loop delay in ms for LRIT (108.8ms per packet @ 64 kbps) elif self.config.downlink == "HRIT": self.coreWait = 1 # Core loop delay in ms for HRIT (2.2ms per packet @ 3 Mbps) # Start core demuxer thread demux_thread = Thread() demux_thread.name = "DEMUX CORE" demux_thread.run = self.demux_core demux_thread.start()
def __init__(self, response_queue=None, key: str = None, logger: logging.Logger = None): # 付费key self.__key = key # 日志模块 if isinstance(logger, logging.Logger): # 使用自定义logger self.logger = logger else: # 使用默认logger self.logger = logging.getLogger(__file__) formatter = logging.Formatter('%(asctime)s [%(threadName)s] %(levelname)s: %(message)s') sh = logging.StreamHandler() sh.setFormatter(formatter) sh.setLevel(logging.DEBUG) self.logger.addHandler(sh) self.logger.setLevel(logging.DEBUG) # response存放队列 if isinstance(response_queue, Queue): self.__response_queue = response_queue else: raise Exception("response_queue must be Queue") self.pids = [] self.__port2client = dict() host = "127.0.0.1" port = 9527 self.__socket_server = socket(AF_INET, SOCK_STREAM) self.__socket_server.bind((host, port)) self.__socket_server.listen(1) t_start_server = Thread(target=self.__start_server) t_start_server.daemon = True t_start_server.name = "spy" t_start_server.start() current_path = os.path.split(os.path.abspath(__file__))[0] helper_path = os.path.join(current_path, "SpyK.exe 3.0") subprocess.Popen(helper_path)
def cgminerThread(): pparams = PoolParams() pparams.url = "http://notroll.in:6332" pparams.username = "******" pparams.password = "******" global THREAD_INTENSITY_CHECKER global THREAD_MINER THREAD_INTENSITY_CHECKER = Thread(target=testIntensityAdjuster) THREAD_MINER = Thread(target=startCGMINER, args=(pparams,)) #must be a tuple THREAD_INTENSITY_CHECKER.name = "Intensity checker thread" THREAD_MINER.name = "Miner control thread" THREAD_MINER.start() THREAD_INTENSITY_CHECKER.start()
def start_thread(name=None, is_daemon=True): new_loop = asyncio.new_event_loop() new_thread = Thread(target=start_loop, args=(new_loop, )) new_thread.name = name new_thread.daemon = is_daemon new_thread.start() return new_loop
def fsinit(self): if self._use_cache: t = Thread(target=self._cache_thread) t.name = "cache loader" t.daemon = True t.start() print "Ready"
def start(self, mm): mm.cycles = 0 self.launch_msfrpc(mm) while True: if mm.run: mm.cycles += 1 logging.info("Beginning cycle #" + str(mm.cycles) + ".") for team in mm.teams: for system in team.systems: # For each system, spawn a master thread if system.status == "Inactive": runner = Thread(target=self.master, args=(mm, team, system)) runner.name = "Team" + str(team.id) + "Sys" + str( system.num) runner.start() else: logging.warning("Not running " + str(system) + " due to being active.") self.housekeeping(mm) else: logging.info("Not running pentesting cycle.") logging.info("Sleeping for 20 seconds.") time.sleep(20)
def get_content(self, filename=None): thread = Thread(target=self._open_file, args=("Covid19/data/" + filename, )) thread.name = "Thread to read" thread.start() thread.join() return self.covidRecord
def init_server(self, address): self.server = Server(self) self.server.rpc = self.rpc self.server.start(address) thread = Thread(target=self.server.serve_forever) thread.name = 'ServerThread' thread.daemon = True thread.start()
def _start_background_tasks(self): """ Start all background tasks. """ tasks = get_special_methods(self._plugin, 'background_task') for task in tasks: thread = Thread(target=PluginRuntime._run_background_task, args=(task,)) thread.name = 'Background thread ({0})'.format(task.__name__) thread.daemon = True thread.start()
def train_network(): global thread global training if not training: thread = Thread(target=training_thread) thread.name = 'trainingThread' emit('training started', thread.name) thread.start() training = True
def start_locator_thread(args): if args.pycurl: search_thread = Thread(target=search_loop_async, args=(args,)) else: search_thread = Thread(target=search_loop, args=(args,)) search_thread.daemon = True search_thread.name = 'search_thread' search_thread.start()
def start_locator_thread(control): global args global search_thread search_loop_start() args.control = control; search_thread = Thread(target=search_loop, args=(args,)) search_thread.daemon = True search_thread.name = 'search_thread' search_thread.start()
def init_server(self, address): self.server = Server(self) self.server.rpc = self.rpc self.server.streaming = True self.server.start(address, transport_options={'permissions': 0o777}) thread = Thread(target=self.server.serve_forever) thread.name = 'ServerThread' thread.daemon = True thread.start()
def start(self): self.stopped.clear() self.threads[:] = [] for i in range(self.thread_count): t = Thread(target = self.run) t.name = "%s-%s" % (self.func.__name__, i + 1) t.daemon = True t.start() self.threads.append(t)
def start_thread(self): '''Starts an active object -- called within __start This will start an active object and the task fabric ''' thread = Thread(target = self.run_event, args=(task_event, self.queue)) thread.name = self.name thread.daemon = True thread.start() return thread
def __init__(self, size, name): self._size = size self._lock = Lock() self._busy_count = 0 self._event = Event() self._job_queue = queue.Queue() for i in range(0, size): thread = Thread(target = self._run_worker) thread.name = "%s.%d" % (name, i + 1) thread.daemon = True thread.start()
def start(self): with self.lock: if not self.running: self.stopped.clear() del self.threads[:] for i in range(self.thread_count): t = Thread(target = self.run) t.name = '{}-{}'.format(self.func.__name__, i + 1) t.daemon = True t.start() self.threads.append(t)
def call(self, hook, data): for name, command in self.resources.items(): if hook in command.hooks and self._wrap_assert(command, data): thread = Thread(target=self._wrap_call, args=(command, data)) start_time = strftime("%b %d %H:%M:%S") thread.name = "command:{0} ({1})".format(command.name, start_time) thread.daemon = True thread.start() self._bot.threads["commands"].append(thread) return
def call(self, hook, data): """Respond to a hook type and a :py:class:`Data` object.""" for command in self: if hook in command.hooks and self._wrap_check(command, data): thread = Thread(target=self._wrap_process, args=(command, data)) start_time = strftime("%b %d %H:%M:%S") thread.name = "irc:{0} ({1})".format(command.name, start_time) thread.daemon = True thread.start() return
def registerService(self, service, servicename): if self.enshureNameserver(): pyrodaemon = Pyro4.core.Daemon(host=self.address) serveruri = pyrodaemon.register(service) self.nameserver.register(servicename, serveruri) serviceHandler = Thread(target=pyrodaemon.requestLoop) serviceHandler.daemon = True serviceHandler.name = 'pyroserver: ' + servicename serviceHandler.start() self.services.append((serveruri, serviceHandler)) else: raise Pyro4.errors.NamingError()
def initiate_thread(thread_obj, name, thread_runner, queue, subscriptions): if thread_obj is None or thread_obj.is_alive() is not True: thread_obj = Thread(target = thread_runner, args=(self.task_event, queue, subscriptions)) thread_obj.name = name thread_obj.daemon = True thread_obj.start() # if we haven't done what we promised, crash the program assert(thread_obj.is_alive() is True) return thread_obj
def on_open(ws): rcvthname = current_thread().name botnum = int(rcvthname[4:]) # remove 'recv' from the beginning of the thread name def startsend(*args): thname = current_thread().name for i in range(NUMMSG): txt = "I'm bot%d and this is msg %d" % (botnum, i) ws.send(txt) #print '%s \t %s SENT: %s' % (time.time(), thname, txt) time.sleep(MSGDELAY) ws.close() th = Thread(target=startsend) th.name = 'send%s' % botnum th.start()
def StartListener( startTime=datetime.datetime.now(), comPort=1, HOST=None, PORT=None ): # HOST, PORT not used. global q global shutdownQ global listener StopListener() if Model.race: comPort = (comPort or getattr(Model.race, 'comPort', 1)) q = Queue() shutdownQ = Queue() listener = Process( target = Server, args=(q, shutdownQ, comPort, startTime) ) listener.name = 'RaceResultUSB Listener' listener.daemon = True listener.start()
def StartListener( startTime = datetime.datetime.now(), HOST = DEFAULT_HOST, PORT = DEFAULT_PORT ): global q global shutdownQ global listener global dateToday dateToday = startTime.date() StopListener() q = Queue() shutdownQ = Queue() listener = Process( target = Server, args=(q, shutdownQ, HOST, PORT, startTime) ) listener.name = 'JChip Listener' listener.daemon = True listener.start()