create task and start to process it in channel (will NOT wait until execution finish)
429971
public Long createAndStartTask(String taskName, String data, String key1, String key2) {
		return tedDriverImpl.createAndExecuteTask(taskName, data, key1, key2, true);
	}
1120584
def execute(self, env, args):
        

        # start the task
        if env.task.start(args.task_name):
            env.io.success(u'Task Loaded.')
300594
def trigger_async(channels, event_name, data, params = {})
      post_async('/events', trigger_params(channels, event_name, data, params))
    end
530092
def execute(self, env, args):
        

        task_name = args.task_name
        clone_task = args.clone_task

        if not env.task.create(task_name, clone_task):
            raise errors.FocusError(u'Could not create task "{0}"'
                                    .format(task_name))

        # open in task config in editor
        if not args.skip_edit:
            task_config = env.task.get_config_path(task_name)

            if not _edit_task_config(env, task_config, confirm=True):
                raise errors.FocusError(u'Could not open task config: {0}'
                                        .format(task_config))
303425
def begin_application(self, req, res):
        
        # Add the middleware processing to the event loop - this *should*
        # change the call stack so any server errors do not link back to this
        # function
        self.loop.create_task(self.http_application.handle_client_request(req, res))
470276
void processTedQueue() {
		int totalProcessing = context.taskManager.calcWaitingTaskCountInAllChannels();
		if (totalProcessing >= TaskManager.LIMIT_TOTAL_WAIT_TASKS) {
			logger.warn("Total size of waiting tasks ({}) already exceeded limit ({}), skip this iteration (2)", totalProcessing, TaskManager.LIMIT_TOTAL_WAIT_TASKS);
			return;
		}
		Channel channel = context.registry.getChannelOrMain(Model.CHANNEL_QUEUE);
		int maxTask = context.taskManager.calcChannelBufferFree(channel);
		maxTask = Math.min(maxTask, 50);
		Map<String, Integer> channelSizes = new HashMap<String, Integer>();
		channelSizes.put(Model.CHANNEL_QUEUE, maxTask);
		List<TaskRec> heads = tedDao.reserveTaskPortion(channelSizes);
		if (heads.isEmpty())
			return;

		for (final TaskRec head : heads) {
			logger.debug("exec eventQueue for '{}', headTaskId={}", head.key1, head.taskId);
			channel.workers.execute(new TedRunnable(head) {
				@Override
				public void run() {
					processEventQueue(head);
				}
			});
		}
	}
53832
private void submitTask(@NotNull State<T, R> state, @NotNull BatchItem item, @NotNull Link auth) {
    // Submit task
    final StateHolder holder = new StateHolder(state);
    try {
      state.auth = auth;
      final Work<R> worker = objectTask(state, item);
      if (state.future.isDone()) {
        holder.close();
        return;
      }
      if (worker == null) {
        throw new IllegalStateException("Uncompleted task worker is null: " + item);
      }
      executeInPool(
          "task: " + state.getMeta().getOid(),
          () -> processObject(state, auth, worker),
          holder::close,
          true
      );
    } catch (Throwable e) {
      holder.close();
      throw e;
    }
  }
101440
def async_task(func, *args, **kwargs):
    """"""
    keywords = kwargs.copy()
    opt_keys = (
    'hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker')
    q_options = keywords.pop('q_options', {})
    # get an id
    tag = uuid()
    # build the task package
    task = {'id': tag[1],
            'name': keywords.pop('task_name', None) or q_options.pop('task_name', None) or tag[0],
            'func': func,
            'args': args}
    # push optionals
    for key in opt_keys:
        if q_options and key in q_options:
            task[key] = q_options[key]
        elif key in keywords:
            task[key] = keywords.pop(key)
    # don't serialize the broker
    broker = task.pop('broker', get_broker())
    # overrides
    if 'cached' not in task and Conf.CACHED:
        task['cached'] = Conf.CACHED
    if 'sync' not in task and Conf.SYNC:
        task['sync'] = Conf.SYNC
    if 'ack_failure' not in task and Conf.ACK_FAILURES:
        task['ack_failure'] = Conf.ACK_FAILURES
    # finalize
    task['kwargs'] = keywords
    task['started'] = timezone.now()
    # signal it
    pre_enqueue.send(sender="django_q", task=task)
    # sign it
    pack = SignedPackage.dumps(task)
    if task.get('sync', False):
        return _sync(pack)
    # push it
    enqueue_id = broker.enqueue(pack)
    logger.info('Enqueued {}'.format(enqueue_id))
    logger.debug('Pushed {}'.format(tag))
    return task['id']
302332
def _bridge(self, channel):
        
        channel.setblocking(False)
        channel.settimeout(0.0)
        self._tasks = [
            gevent.spawn(self._forward_inbound, channel),
            gevent.spawn(self._forward_outbound, channel)
        ]
        gevent.joinall(self._tasks)
381263
async def run_gen_task(self, container, gentask, newthread = True):
        ""
        e = TaskEvent(self, gen_task = gentask, newthread = newthread)
        await container.wait_for_send(e)
        ev = await TaskDoneEvent.createMatcher(e)
        if hasattr(ev, 'exception'):
            raise ev.exception
        else:
            return ev.result
1020271
async def run_async(self, endpoint: str):
        
        self._connect(endpoint)

        # spawn an initial listen task
        listen_task = asyncio.ensure_future(self._socket.recv_multipart())
        task_list = [listen_task]

        while True:
            dones, pendings = await asyncio.wait(task_list, return_when=asyncio.FIRST_COMPLETED)

            # grab one "done" task to handle
            task_list, done_list = list(pendings), list(dones)
            done = done_list.pop()
            task_list += done_list

            if done == listen_task:
                try:
                    # empty_frame may either be:
                    # 1. a single null frame if the client is a REQ socket
                    # 2. an empty list (ie. no frames) if the client is a DEALER socket
                    identity, *empty_frame, msg = done.result()
                    request = from_msgpack(msg)

                    # spawn a processing task
                    task_list.append(asyncio.ensure_future(
                        self._process_request(identity, empty_frame, request)))
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'reception: {}'.format(str(e)))
                    else:
                        raise e
                finally:
                    # spawn a new listen task
                    listen_task = asyncio.ensure_future(self._socket.recv_multipart())
                    task_list.append(listen_task)
            else:
                # if there's been an exception during processing, consider reraising it
                try:
                    done.result()
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'dispatch: {}'.format(str(e)))
                    else:
                        raise e
774676
function task(callback) {
	// spawn phantomas process
	var child = phantomas(url, options, function(err, data, results) {
		callback(
			null, // pass null even in case of an error to continue async.series processing (issue #380)
			[err, results]
		);
	});

	child.on('progress', function(progress, inc) {
		if (bar) {
			bar.tick(inc);
		}
	});

	// pipe --verbose messages to stderr
	child.stderr.pipe(process.stderr);
}
1159248
def start(self):
        """"""
        self.run_task = self.pyvlx.loop.create_task(
            self.loop())
693389
def task_transaction(channel):
    """"""
    with channel.lock:
        if channel.poll(0):
            task = channel.recv()
            channel.send(Acknowledgement(os.getpid(), task.id))
        else:
            raise RuntimeError("Race condition between workers")

    return task
719543
async def start_task(self, task: Task) -> None:
        ''''''

        try:
            Log.debug('task %s starting', task.name)
            before = time.time()
            task.counters['last_run'] = before

            task.running = True
            self.running_tasks.add(task)
            await task.run_task()
            Log.debug('task %s completed', task.name)

        except CancelledError:
            Log.debug('task %s cancelled', task.name)

        except Exception:
            Log.exception('unhandled exception in task %s', task.name)

        finally:
            self.running_tasks.discard(task)
            task.running = False
            task.task = None

            after = time.time()
            total = after - before
            task.counters['last_completed'] = after
            task.counters['duration'] = total
931140
def make_reader_task(self, stream, callback):
        

        return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback))
72252
def _run_task(task, start_message, finished_message):
    

    # Get the hosts and record the start time
    env.hosts = fabconf['EC2_INSTANCES']
    start = time.time()

    # Check if any hosts exist
    if env.hosts == []:
        print("There are EC2 instances defined in project_conf.py, please add some instances and try again")
        print("or run 'fab spawn_instance' to create an instance")
        return

    # Print the starting message
    print(_yellow(start_message))

    # Run the task items
    for item in task:
        try:
            print(_yellow(item['message']))
        except KeyError:
            pass
        globals()["_" + item['action']](item['params'])

    # Print the final message and the elapsed time
    print(_yellow("%s in %.2fs" % (finished_message, time.time() - start)))