Poll this method for completed / pending / failed / cancelled status
179831
def transaction_status(token)
      payload = { :token => token }
      result = http_json_request(MPower::Setup.direct_mobile_tx_status_base_url,payload)

      if result["response_code"] == "00"
        @tx_status = result["tx_status"]
        @mobile_invoice_no = result["mobile_invoice_no"]
        @cancel_reason = result["cancel_reason"]
        push_results(result)
        true
      else
        push_results(result)
        false
      end
    end
661191
def _check_for_pending(self, *args, **kwargs):
        
        if self._notification_pending and not self._processing:
            self._processing = True
            args, kwargs = self._data
            self._notify(*args, **kwargs)
            self._notification_pending = False
            self._processing = False
781418
def _view_finish(self, queue_type, queue_id, job_id):
        """"""
        response = {
            'status': 'failure'
        }
        request_data = {
            'queue_type': queue_type,
            'queue_id': queue_id,
            'job_id': job_id
        }

        try:
            response = self.sq.finish(**request_data)
            if response['status'] == 'failure':
                return jsonify(**response), 404
        except Exception, e:
            response['message'] = e.message
            return jsonify(**response), 400

        return jsonify(**response)
697332
def get_status(self, response, finished=False):
        """"""
        lines = [line.strip() for line in response.split("\n")
                if line.strip() != '']
        last_line = lines[-1]
        if last_line.startswith('qstat: Unknown Job'):
            return COMPLETED
        else:
            try:
                status = lines[-1].split()[4]
                return self.status_mapping[status]
            except (IndexError, KeyError):
                return None
482703
def done(self, warn=True):
        """"""
        if not self.process:
            raise Exception("Not implemented yet or process not started yet, make sure to overload the done() method in your Experiment class")
        self.process.poll()
        if self.process.returncode == None:
            return False
        elif self.process.returncode > 0:
            raise ProcessFailed()
        else:
            self.endtime = datetime.datetime.now()
            return True
956263
def _do_poll_problems(self):
        
        try:
            # grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)
            frame_futures = {}

            def task_done():
                self._poll_queue.task_done()

            def add(future):
                # add future to query frame_futures
                # returns: worker lives on?

                # `None` task signifies thread termination
                if future is None:
                    task_done()
                    return False

                if future.id not in frame_futures and not future.done():
                    frame_futures[future.id] = future
                else:
                    task_done()

                return True

            while True:
                frame_futures.clear()

                # blocking add first scheduled
                frame_earliest, future = self._poll_queue.get()
                if not add(future):
                    return

                # try grouping if scheduled within grouping timeframe
                while len(frame_futures) < self._STATUS_QUERY_SIZE:
                    try:
                        task = self._poll_queue.get_nowait()
                    except queue.Empty:
                        break

                    at, future = task
                    if at - frame_earliest <= self._POLL_GROUP_TIMEFRAME:
                        if not add(future):
                            return
                    else:
                        task_done()
                        self._poll_queue.put(task)
                        break

                # build a query string with ids of all futures in this frame
                ids = [future.id for future in frame_futures.values()]
                _LOGGER.debug("Polling for status of futures: %s", ids)
                query_string = 'problems/?id=' + ','.join(ids)

                # if futures were cancelled while `add`ing, skip empty frame
                if not ids:
                    continue

                # wait until `frame_earliest` before polling
                delay = frame_earliest - time.time()
                if delay > 0:
                    _LOGGER.debug("Pausing polling %.2f sec for futures: %s", delay, ids)
                    time.sleep(delay)
                else:
                    _LOGGER.trace("Skipping non-positive delay of %.2f sec", delay)

                try:
                    _LOGGER.trace("Executing poll API request")

                    try:
                        response = self.session.get(posixpath.join(self.endpoint, query_string))
                    except requests.exceptions.Timeout:
                        raise RequestTimeout

                    if response.status_code == 401:
                        raise SolverAuthenticationError()
                    response.raise_for_status()

                    statuses = response.json()
                    for status in statuses:
                        self._handle_problem_status(status, frame_futures[status['id']])

                except BaseException as exception:
                    if not isinstance(exception, SolverAuthenticationError):
                        exception = IOError(exception)

                    for id_ in frame_futures.keys():
                        frame_futures[id_]._set_error(IOError(exception), sys.exc_info())

                for id_ in frame_futures.keys():
                    task_done()

                time.sleep(0)

        except Exception as err:
            _LOGGER.exception(err)
139696
def wait_one(self):
        """"""
        while True:
            try:
                item = self.output_queue.get(True, self.polltime)
            except Queue.Empty:
                continue
            except KeyboardInterrupt:
                LOGGER.debug('Exiting')
                return
            else:
                item.check_result()
                return
983801
private void checkStatus(MtasSolrStatus status) throws IOException {
		if (!status.finished()) {
			if (status.error()) {
				status.setFinished();
				if (requestHandler != null) {
					requestHandler.finishStatus(status);
				}
				throw new IOException(status.errorMessage());
			} else if (status.abort()) {
				status.setFinished();
				if (requestHandler != null) {
					requestHandler.finishStatus(status);
				}
				throw new IOException(status.abortMessage());
			}
		}
	}
631583
def _polling_iteration(self):
		
		if self.__task is None:
			self.ready_event().set()
		elif self.__task.check_events() is True:
			self.ready_event().set()
			self.registry().task_finished(self)
1054581
def _blocking_poll(self, timeout=None):
        
        if self._result_set:
            return

        retry_ = self._retry.with_deadline(timeout)

        try:
            retry_(self._done_or_raise)()
        except exceptions.RetryError:
            raise concurrent.futures.TimeoutError(
                "Operation did not complete within the designated " "timeout."
            )
576364
public boolean isFinished() {
    // If we have a HandshakeResult, we are done.
    if (result != null) {
      return true;
    }
    // If we have an error status, we are done.
    if (status != null && status.getCode() != Status.Code.OK.value()) {
      return true;
    }
    return false;
  }
1246539
def _set_future_result(self):
        """"""
        # This must be done in a lock to prevent the polling thread
        # and main thread from both executing the completion logic
        # at the same time.
        with self._completion_lock:
            # If the operation isn't complete or if the result has already been
            # set, do not call set_result/set_exception again.
            # Note: self._result_set is set to True in set_result and
            # set_exception, in case those methods are invoked directly.
            if self.state != _DONE_STATE or self._result_set:
                return

            if self.error_result is not None:
                exception = _error_result_to_exception(self.error_result)
                self.set_exception(exception)
            else:
                self.set_result(self)
923799
def status(self, status):
        
        allowed_values = ["pending", "awaitingRetry", "successful", "failed"]
        if status is not None and status not in allowed_values:
            raise ValueError(
                "Invalid value for `status` ({0}), must be one of {1}"
                .format(status, allowed_values)
            )

        self._status = status
730517
def poll(self):
        """"""
        queue_empty = self.server.get_queue_empty_exception()
        try:
            packets = [self.queue.get(timeout=self.server.ping_timeout)]
            self.queue.task_done()
        except queue_empty:
            raise exceptions.QueueEmpty()
        if packets == [None]:
            return []
        while True:
            try:
                packets.append(self.queue.get(block=False))
                self.queue.task_done()
            except queue_empty:
                break
        return packets
159456
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
        '''

        '''
        if self.config['api_key'] is None:
            raise ValueError('config api_key is undefined')

        if offset or self.config.get('offset', None):
            self.offset = offset or self.config.get('offset', None)

        self._start()

        while True:
            try:
                response = self.get_updates(poll_timeout, self.offset)
                if response.get('ok', False) is False:
                    raise ValueError(response['error'])
                else:
                    self.process_updates(response)
            except Exception as e:
                print('Error: Unknown Exception')
                print(e)
                if debug:
                    raise e
                else:
                    time.sleep(cooldown)
562689
protected void poll() {
        int missCount = 0;
        String curQueue = null;
        while (RUNNING.equals(this.state.get())) {
            try {
                if (threadNameChangingEnabled) {
                    renameThread("Waiting for " + JesqueUtils.join(",", this.queueNames));
                }
                curQueue = getNextQueue();
                if (curQueue != null) {
                    checkPaused();
                    // Might have been waiting in poll()/checkPaused() for a while
                    if (RUNNING.equals(this.state.get())) {
                        this.listenerDelegate.fireEvent(WORKER_POLL, this, curQueue, null, null, null, null);
                        final String payload = pop(curQueue);
                        if (payload != null) {
                            process(ObjectMapperFactory.get().readValue(payload, Job.class), curQueue);
                            missCount = 0;
                        } else {
                            missCount++;
                            if (shouldSleep(missCount) && RUNNING.equals(this.state.get())) {
                                // Keeps worker from busy-spinning on empty queues
                                missCount = 0;
                                Thread.sleep(EMPTY_QUEUE_SLEEP_TIME);
                            }
                        }
                    }
                }
            } catch (InterruptedException ie) {
                if (!isShutdown()) {
                    recoverFromException(curQueue, ie);
                }
            } catch (JsonParseException | JsonMappingException e) {
                // If the job JSON is not deserializable, we never want to submit it again...
                removeInFlight(curQueue, true);
                recoverFromException(curQueue, e);
            } catch (Exception e) {
                recoverFromException(curQueue, e);
            }
        }
    }
448452
def refresh_if_needed(self):
        
        if self.state in (self.PENDING, self.STARTED):
            try:
                response, = self._fetch_result()['tasks']
            except (KeyError, ValueError):
                raise Exception(
                    "Unable to find results for task."
                )

            if 'error' in response:
                self.state == self.FAILURE
                raise ServerError(response['error'])

            if 'state' in response:
                self.state = response['state']
                self.result = response['result']