This must be called fro your activity to start listening for task
Perform Sfn long polling and call user callback function when receiving new activity
514977
public function doActivity()
    {
        $context = [
            'activityArn' => $this->arn,
            'workerName'  => $this->name
        ];

        $this->cpeLogger->logOut("INFO", basename(__FILE__),
                                 "Starting '$this->name' activity tasks polling");

        do {

            try {
                if ($this->debug)
                    $this->cpeLogger->logOut("DEBUG", basename(__FILE__),
                                             "Polling for '$this->name' activity...");

                // Perform Sfn long polling and wait for new tasks to process
                $task = $this->cpeSfnHandler->sfn->getActivityTask($context);

            } catch (\Exception $e) {
                $this->cpeLogger->logOut("ERROR", basename(__FILE__),
                                         "Sfn getActivityTask Failed! " . $e->getMessage(),
                                         $this->logKey);

                // Notify the client if any
                // if ($this->client)
                //     $this->client->onException($context, $e);
            }

            try {
                // Do we have a new activity?
                if (isset($task['taskToken']) && $task['taskToken'] != '') {

                    $this->cpeLogger->logOut("INFO", basename(__FILE__),
                                             "\033[1mNew activity '$this->name' triggered!\033[0m Token: ".$task['taskToken'].".\nSee the Log file for this token: ".$this->cpeLogger->logPath);

                    // Set the logKey so a new log file will be created just for this Execution
                    $this->logKey = substr($task['taskToken'],
                                           strlen($task['taskToken'])-16,
                                           strlen($task['taskToken']) - (strlen($task['taskToken']) - 16));
                    $this->logKey = preg_replace('/[\\\\\/\%\[\]\.\(\)-\/]/s', "_", $this->logKey);
                    $this->token  = $task['taskToken'];
                    if ($this->client)
                        $this->client->logKey = $this->logKey;

                    // Validate the JSON input and set `$this->input`
                    $this->doInputValidation($task['input']);

                    // Notify the client if any
                    if ($this->client)
                        $this->client->onStart($task);

                    // Call the user callback function with the activity input for processing
                    $result = $this->process($task);

                    // Execution successful. We mark it as such and return the output to Sfn
                    $this->activitySuccess($result);
                }
            } catch (\Exception $e) {
                // Notify Sfn that the activity has failed
                $this->activityFail($this->name."Exception", $e->getMessage());
            } finally {
                if (!empty($this->inputFilePath)) {
                    // Remove input file that may have been used. Just to be sure.
                    unlink($this->inputFilePath);
                    $this->inputFilePath = null;
                }
            }

        } while (42);
    }
774132
private void notifyHandlers(Room sfsRoom, User sfsUser) {
        ApiRoom apiRoom = AgentUtil.getRoomAgent(sfsRoom);
        ApiUser apiUser = AgentUtil.getUserAgent(sfsUser);
        for(RoomHandlerClass handler : handlers) {
            Object userAgent = checkUserAgent(handler, apiUser);
            if(!checkHandler(handler, apiRoom, userAgent))
                continue;
            Object instance = handler.newInstance();
            callHandleMethod(handler.getHandleMethod(), 
                    instance, apiRoom, userAgent);
        }
    }
782100
void onClickNew() {

        try {
            CmsObject cms = A_CmsUI.getCmsObject();

            CmsResource folderRes = cms.readResource(m_currentFolder, CmsResourceFilter.IGNORE_EXPIRATION);
            I_CmsDialogContext newDialogContext = getDialogContext();

            CmsNewDialog newDialog = new CmsNewDialog(folderRes, newDialogContext);
            newDialogContext.start(
                CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_NEWRESOURCEDIALOG_TITLE_0),
                newDialog);

        } catch (Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
654221
@Override
	public boolean onActivityTimeout() throws Exception
    {
    	try
    	{
    		send(new PingQuery());
    		return false;
    	}
    	catch (Exception e)
    	{
    		log.warn("#"+id+" cannot send ping to server : "+e.toString());
    		return true;
    	}
    }
587976
private ListenableFuture<TaskStatus> attachCallbacks(final Task task, final ListenableFuture<TaskStatus> statusFuture)
  {
    final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder();
    IndexTaskUtils.setTaskDimensions(metricBuilder, task);

    Futures.addCallback(
        statusFuture,
        new FutureCallback<TaskStatus>()
        {
          @Override
          public void onSuccess(final TaskStatus status)
          {
            log.info("Received %s status for task: %s", status.getStatusCode(), status.getId());
            handleStatus(status);
          }

          @Override
          public void onFailure(final Throwable t)
          {
            log.makeAlert(t, "Failed to run task")
               .addData("task", task.getId())
               .addData("type", task.getType())
               .addData("dataSource", task.getDataSource())
               .emit();
            handleStatus(TaskStatus.failure(task.getId()));
          }

          private void handleStatus(final TaskStatus status)
          {
            try {
              // If we're not supposed to be running anymore, don't do anything. Somewhat racey if the flag gets set
              // after we check and before we commit the database transaction, but better than nothing.
              if (!active) {
                log.info("Abandoning task due to shutdown: %s", task.getId());
                return;
              }

              notifyStatus(task, status, "notified status change from task");

              // Emit event and log, if the task is done
              if (status.isComplete()) {
                IndexTaskUtils.setTaskStatusDimensions(metricBuilder, status);
                emitter.emit(metricBuilder.build("task/run/time", status.getDuration()));

                log.info(
                    "Task %s: %s (%d run duration)",
                    status.getStatusCode(),
                    task,
                    status.getDuration()
                );

                if (status.isSuccess()) {
                  Counters.incrementAndGetLong(totalSuccessfulTaskCount, task.getDataSource());
                } else {
                  Counters.incrementAndGetLong(totalFailedTaskCount, task.getDataSource());
                }
              }
            }
            catch (Exception e) {
              log.makeAlert(e, "Failed to handle task status")
                 .addData("task", task.getId())
                 .addData("statusCode", status.getStatusCode())
                 .emit();
            }
          }
        }
    );
    return statusFuture;
  }
1370116
public void execute() throws ActivityException {
        EventWaitInstance received = registerWaitEvents(false, true);
        if (received!=null) {
            setReturnCodeAndExitStatus(received.getCompletionCode());
            processMessage(getExternalEventInstanceDetails(received.getMessageDocumentId()));
            boolean toFinish = handleCompletionCode();
            if (toFinish && exitStatus==null)
                exitStatus = WorkStatus.STATUS_COMPLETED;
        } else {
            exitStatus = WorkStatus.STATUS_COMPLETED;
            setReturnCode(null);
        }
    }
419700
@Override
    public synchronized void resume() {
        this.paused = false;
        ServerActivityCallback listener = listenerUpdater.get(this);
        if (listener != null) {
            listenerUpdater.compareAndSet(this, listener, null);
        }
        while (!taskQueue.isEmpty() && (activeRequestCount < maxRequestCount || maxRequestCount < 0)) {
            runQueuedTask(false);
        }
    }
1264251
private void requestNotificationListener() {
        AndPermission.with(this)
            .notification()
            .listener()
            .rationale(new NotifyListenerRationale())
            .onGranted(new Action<Void>() {
                @Override
                public void onAction(Void data) {
                    toast(R.string.successfully);
                }
            })
            .onDenied(new Action<Void>() {
                @Override
                public void onAction(Void data) {
                    toast(R.string.failure);
                }
            })
            .start();
    }
774092
@Override
    public synchronized void onOpen() {
        super.onOpen();

        if (phoneStateListener == null) {
            Handler mainHandler = new Handler(context.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    phoneStateListener = new PhoneStateListener() {

                        @Override
                        public void onCellInfoChanged(List<CellInfo> cellInfo) {
                            if (cellInfo != null && !cellInfo.isEmpty()) {
                                onCellsChanged(cellInfo);
                            } else if (supportsCellInfoChanged) {
                                supportsCellInfoChanged = false;
                                onSignalStrengthsChanged(null);
                            }
                        }

                        @Override
                        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                            if (!supportsCellInfoChanged) {
                                fallbackScan();
                            }
                        }
                    };
                    registerPhoneStateListener();
                }
            });
        } else {
            registerPhoneStateListener();
        }
    }
574612
void triggerSessionRequested(Jingle initJin) {

        JingleSessionRequestListener[] jingleSessionRequestListeners;

        // Make a synchronized copy of the listenerJingles
        synchronized (this.jingleSessionRequestListeners) {
            jingleSessionRequestListeners = new JingleSessionRequestListener[this.jingleSessionRequestListeners.size()];
            this.jingleSessionRequestListeners.toArray(jingleSessionRequestListeners);
        }

        // ... and let them know of the event
        JingleSessionRequest request = new JingleSessionRequest(this, initJin);
        for (int i = 0; i < jingleSessionRequestListeners.length; i++) {
            jingleSessionRequestListeners[i].sessionRequested(request);
        }
    }
748435
def add_listener(self, event_type, callback):
        """"""

        if not self.connected:
            # wait for errors set by reraise method
            time.sleep(1)
            if self.exception:
                # pylint: disable=raising-bad-type
                raise self.exception
            raise ConnectionError(f"{self.room} is not connected")

        thread = get_thread_ident()
        with self.lock:
            listener = self.listeners[thread]
        listener.add(event_type, callback)
        # use "initial_files" event to listen for whole filelist on room join
        self.process_queues()
861106
private ExecutionCallback<Boolean> loadingFinishedCallback() {
        return new ExecutionCallback<Boolean>() {
            @Override
            public void onResponse(Boolean loadingFinished) {
                if (loadingFinished) {
                    updateLocalKeyLoadStatus(null);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                updateLocalKeyLoadStatus(t);
            }
        };
    }
1218586
private static Runnable asRunnable(final ClientTransport.PingCallback callback,
                                     final long roundTripTimeNanos) {
    return new Runnable() {
      @Override
      public void run() {
        callback.onSuccess(roundTripTimeNanos);
      }
    };

  }
109914
private void notifyListener(RequestResponseClass clazz, 
	        ISFSObject params, User user, Object userAgent) throws Exception {
	    Object listener = clazz.newInstance();
	    setDataToListener(clazz, listener, params);
	    invokeExecuteMethod(clazz.getExecuteMethod(), listener, userAgent);
	    responseClient(clazz, listener, user);
	}
1334616
private void updateActivity(ActivityType type, String name, String streamingUrl) {
        if (name == null) {
            activity = null;
        } else if (streamingUrl == null) {
            activity = new ActivityImpl(type, name, null);
        } else {
            activity = new ActivityImpl(type, name, streamingUrl);
        }
        websocketAdapter.updateStatus();
    }
960071
function onActivity(e) {
      if (!_shouldActivityUpdate(e)) return;
      if (_shouldRestart()) return dispatch(context.actions.start());
      /** THIS WILL BE ROUTED TO FAST OR LOCAL STATE IF ENABLED */
      setState(_constants.IDLEMONITOR_ACTIVITY, { lastActive: +new Date(), lastEvent: { x: e.pageX, y: e.pageY } });
    }
1309827
function updateTask(task, callback) {
    database.serialize(function() {
      var expiry_time = getExpiryTime(task);
      var update_task = "UPDATE "+table_name+" SET task = ?, "
      +"at = datetime("+expiry_time+") WHERE "+table_name+".id = ?";

      log.debug('sqlite-adapter','Running query:',update_task);
      database.run(update_task, JSON.stringify(task), task.id, function(error) {
        if (error) {
          callback(error);
        }
        callback(error, this.changes);
      });
    });
  }