Add the job to the delayed list (zset) of the queue.
511640
def delay_job(self, job, delayed_until):
        
        timestamp = datetime_to_score(delayed_until)
        self.delayed.zadd(timestamp, job.ident)
547556
def schedule_job(self, job):
        
        l = _reraise_with_traceback(job.get_lambda_to_execute())

        future = self.workers.submit(l, update_progress_func=self.update_progress, cancel_job_func=self._check_for_cancel)

        # assign the futures to a dict, mapping them to a job
        self.job_future_mapping[future] = job
        self.future_job_mapping[job.job_id] = future

        # callback for when the future is now!
        future.add_done_callback(self.handle_finished_future)
        # add the job to our cancel notifications data structure, with False at first
        self.cancel_notifications[job.job_id] = False

        return future
111627
def run_later(self, callable_, timeout, *args, **kwargs):
        

        self.lock.acquire()
        try:
            if self.die:
                raise RuntimeError('This timer has been shut down and '
                                   'does not accept new jobs.')

            job = TimerTask(callable_, *args, **kwargs)
            self._jobs.append((job, time.time() + timeout))
            self._jobs.sort(key=lambda j: j[1])  # sort on time
            self.lock.notify()

            return job
        finally:
            self.lock.release()
77285
def enqueue_or_delay(self, queue_name=None, priority=None,
                         delayed_until=None, prepend=False, queue_model=None):
        
        queue_name = self._get_queue_name(queue_name)

        fields = {'queued': '1'}

        if priority is not None:
            fields['priority'] = priority
        else:
            priority = self.priority.hget()

        in_the_future = delayed_until and delayed_until > datetime.utcnow()

        if in_the_future:
            fields['delayed_until'] = str(delayed_until)
            fields['status'] = STATUSES.DELAYED
        else:
            self.delayed_until.delete()
            fields['status'] = STATUSES.WAITING

        self.hmset(**fields)

        if queue_model is None:
            queue_model = self.queue_model
        queue = queue_model.get_queue(queue_name, priority)

        if in_the_future:
            queue.delay_job(self, delayed_until)
        else:
            queue.enqueue_job(self, prepend)
167227
async def put(self, data, ttl=None, ttr=None, delay=None):
        
        the_tuple = await self.queue.put(self, data, ttl=ttl, ttr=ttr, delay=delay)
        if the_tuple.rowcount:
            return Task.create_from_tuple(self, the_tuple)
605545
public function later($delay, $job, $data = '', $queue = null)
    {
        $this->jobs[] = [
            'type'  => 'later',
            'delay' => $delay,
            'job'   => $job,
            'data'  => $data,
            'queue' => $queue,
        ];
    }
379855
def run(delayed, concurrency, version_type=None, queue=None,
        raise_on_error=True):
    """"""
    if delayed:
        celery_kwargs = {
            'kwargs': {
                'version_type': version_type,
                'es_bulk_kwargs': {'raise_on_error': raise_on_error},
            }
        }
        click.secho(
            'Starting {0} tasks for indexing records...'.format(concurrency),
            fg='green')
        if queue is not None:
            celery_kwargs.update({'queue': queue})
        for c in range(0, concurrency):
            process_bulk_queue.apply_async(**celery_kwargs)
    else:
        click.secho('Indexing records...', fg='green')
        RecordIndexer(version_type=version_type).process_bulk_queue(
            es_bulk_kwargs={'raise_on_error': raise_on_error})
1024461
def pending_tasks(self, res):
        ""
        jobs, lock = self._jobs
        with lock:
            return jobs[res].copy()
1218230
public function pushQueue()
    {
        $delay = $this->schedule_timestamp - time();

        if ($delay < 1) {
            $delay = 0;
        }

        Yii::$app->adminqueue->delay($delay)->push(new ScheduleJob(['schedulerId' => $this->id]));
    }
428512
def enqueue_job(self, job, prepend=False):
        
        push_method = getattr(self.waiting, 'lpush' if prepend else 'rpush')
        push_method(job.ident)
946229
def _main_loop(self):
        
        fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay)
        fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay)

        while not self.must_stop():
            self.set_status('waiting')

            if self.last_update_keys + fetch_priorities_delay < datetime.utcnow():
                self.update_keys()

            if self.last_requeue_delayed + fetch_delayed_delay < datetime.utcnow():
                self.requeue_delayed_jobs()

            try:
                queue_and_job = self.wait_for_job()
                if queue_and_job is None:
                    # timeout for blpop
                    continue
                queue, job = queue_and_job
            except Exception as e:
                self.log('Unable to get job: %s\n%s'
                    % (str(e), traceback.format_exc()), level='error')
            else:
                self.num_loops += 1
                try:
                    identifier = 'pk:%s' % job.pk.get()
                except Exception as e:
                    identifier = '??'
                try:
                    self.set_status('running')
                    identifier, status = job.hmget('identifier', 'status')
                     # some cache, don't count on it on subclasses
                    job._cached_identifier = identifier
                    job._cached_status = status
                    queue._cached_name = queue.name.hget()

                    if status == STATUSES.DELAYED:
                        self.job_delayed(job, queue)
                    elif status != STATUSES.WAITING:
                        self.job_skipped(job, queue)
                    else:
                        try:
                            self.job_started(job, queue)
                            job_result = self.callback(job, queue)
                        except Exception as e:
                            trace = None
                            if self.save_tracebacks:
                                trace = traceback.format_exc()
                            self.job_error(job, queue, e, trace)
                        else:
                            job._cached_status = job.status.hget()
                            if job._cached_status == STATUSES.DELAYED:
                                self.job_delayed(job, queue)
                            elif job._cached_status == STATUSES.CANCELED:
                                self.job_skipped(job, queue)
                            else:
                                self.job_success(job, queue, job_result)
                except Exception as e:
                    self.log('[%s] unexpected error: %s\n%s'
                        % (identifier, str(e), traceback.format_exc()), level='error')
                    try:
                        queue.errors.rpush(job.ident)
                    except Exception as e:
                        self.log('[%s] unable to add the error in the queue: %s\n%s'
                            % (identifier, str(e), traceback.format_exc()), level='error')
144187
def enqueue(self, job):
    
    if job.queue_name():
      raise EnqueueError("job %s already queued!" % job.job_id)
    new_len = self.redis.lpush(self.queue_name, job.serialize())
    job.notify_queued(self)
    return new_len
427295
def insert(cls, jobs_data, queue=None, statuses_no_storage=None, return_jobs=True, w=None, j=None):
        

        now = datetime.datetime.utcnow()
        for data in jobs_data:
            if data["status"] == "started":
                data["datestarted"] = now

        no_storage = (statuses_no_storage is not None) and ("started" in statuses_no_storage)
        if no_storage and return_jobs:
            for data in jobs_data:
                data["_id"] = ObjectId()  # Give the job a temporary ID
        else:
            inserted = context.connections.mongodb_jobs.mrq_jobs.insert(
                jobs_data,
                manipulate=True,
                w=w,
                j=j
            )

        if return_jobs:
            jobs = []
            for data in jobs_data:
                job = cls(data["_id"], queue=queue)
                job.set_data(data)
                job.statuses_no_storage = statuses_no_storage
                job.stored = (not no_storage)
                if data["status"] == "started":
                    job.datestarted = data["datestarted"]
                jobs.append(job)

            return jobs
        else:
            return inserted
62864
private void makeJobRunning(JobInProgress job, JobSchedulingInfo oldInfo, 
                              QueueInfo qi) {
    // Removing of the job from job list is responsibility of the
    //initialization poller.
    // Add the job to the running queue
    qi.addRunningJob(job);
  }
348901
public function later($delay, $job, $data = '', $queue = null)
    {
        return $this->pushToDatabase($queue, $this->createPayload(
            $job, $this->getQueue($queue), $data
        ), $delay);
    }
1130509
def push(description, datasets, wait, verbose):
    """"""
    # Loading config
    config = _get_config()
    file_patterns = config["contents"]
    if not isinstance(file_patterns, type([])):
        # put it into an array so we can iterate it, if it isn't already an array
        file_patterns = [file_patterns]
    if datasets:
        datasets_string = datasets.split(',')
    else:
        datasets_string = config.get("datasets", '')


    # Getting all file names/globs -- making sure we get CONFIG_FILE
    files = {CONFIG_FILE}  # use a set so we don't get duplicates
    for pattern in file_patterns:
        files.update(glob.glob(pattern))
    if not files:
        print "No files could be found? Check your contents section in `CONFIG_FILE`!"
        exit(-1)

    if verbose:
        print ""
        print "gatherered files:"
        for path in files:
            print "\t", path
        print ""

    # Zipping
    _print("zipping...")

    if not os.path.exists("brains_history"):
        os.mkdir("brains_history")

    zip_path = 'brains_history/%s.zip' % str(datetime.datetime.now())
    with ZipFile(zip_path, 'w') as zip_file:
        for path in files:
            zip_file.write(path)
    cprint("done", 'green')

    # Sending to server
    with open(zip_path, 'rb') as zip_file:
        _print("sending to server...")
        try:
            response = requests.post(
                URL_SUBMIT,
                files={
                    "zip_file": zip_file,
                },
                data={
                    "name": config["name"],
                    "description": description or '',
                    "languages": config["languages"],
                    "datasets": datasets_string,
                    "wait": wait,
                },
                stream=wait  # if we're waiting for response then stream
            )

            if response.status_code == 200:
                cprint("done", 'green')

                if wait:
                    _print("\nOutput: ")
                    cprint(" " * 72, 'green', attrs=('underline',))

                    chunk_buffer = ""
                    # read in 1 chunk at a time for carriage return detection
                    for chunk in response.iter_content(chunk_size=1):
                        chunk_buffer += chunk

                        if chunk == '\r':
                            # We hit the end of a message!
                            try:
                                data = json.loads(chunk_buffer)
                                if "stdout" not in data or "stderr" not in data:
                                    print "dis one"
                                    continue
                            except (ValueError,):
                                continue

                            if data["stdout"]:
                                # Get rid of termination string, if it's there
                                data["stdout"] = data["stdout"].replace("-%-%-%-%-END BRAIN SEQUENCE-%-%-%-%-", "")
                                _print(data["stdout"])
                            if data["stderr"]:
                                _print(colored(data["stderr"], 'red'))

                            # Clear buffer after reading message
                            chunk_buffer = ""
            else:
                cprint(response.json()["error"], 'red')
        except requests.exceptions.ConnectionError:
            cprint("failed to connect to server!", 'red')
            exit(-2)
210800
def run(name, params, delay):
    '''
    
    '''
    args = [p for p in params if '=' not in p]
    kwargs = dict(p.split('=') for p in params if '=' in p)

    if name not in celery.tasks:
        exit_with_error('Job %s not found', name)
    job = celery.tasks[name]
    label = job_label(name, args, kwargs)
    if delay:
        log.info('Sending job %s', label)
        job.delay(*args, **kwargs)
        log.info('Job sended to workers')
    else:
        log.info('Running job %s', label)
        job.run(*args, **kwargs)
        log.info('Job %s done', name)