Move scheduled job to another minion or minions.

    CLI Example:

    .. code-block:: bash

        salt '*' schedule.move jobname target
165872
def move(name, target, **kwargs):
    '''
    
    '''

    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False

    if 'test' in kwargs and kwargs['test']:
        ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name)
    else:
        opts_schedule = list_(show_all=True, where='opts', return_yaml=False)
        pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False)

        if name in opts_schedule:
            schedule_data = opts_schedule[name]
            where = None
        elif name in pillar_schedule:
            schedule_data = pillar_schedule[name]
            where = 'pillar'
        else:
            ret['comment'] = 'Job {0} does not exist.'.format(name)
            ret['result'] = False
            return ret

        schedule_opts = []
        for key, value in six.iteritems(schedule_data):
            temp = '{0}={1}'.format(key, value)
            schedule_opts.append(temp)
        response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts)

        # Get errors and list of affeced minions
        errors = []
        minions = []
        for minion in response:
            minions.append(minion)
            if not response[minion]:
                errors.append(minion)

        # parse response
        if not response:
            ret['comment'] = 'no servers answered the published schedule.add command'
            return ret
        elif errors:
            ret['comment'] = 'the following minions return False'
            ret['minions'] = errors
            return ret
        else:
            delete(name, where=where)
            ret['result'] = True
            ret['comment'] = 'Moved Job {0} from schedule.'.format(name)
            ret['minions'] = minions
            return ret
    return ret
894555
def reschedule(self, date, callable_name=None, content_object=None,
                   expires='7d', args=None, kwargs=None):
        """"""
        # Resolve date relative to the expected start of the current job.
        if isinstance(date, basestring):
            date = parse_timedelta(date)
        if isinstance(date, datetime.timedelta):
            date = self.time_slot_start + date

        if callable_name is None:
            callable_name = self.callable_name
        if content_object is None:
            content_object = self.content_object
        if args is None:
            args = self.args or []
        if kwargs is None:
            kwargs = self.kwargs or {}
        from django_future import schedule_job
        return schedule_job(date, callable_name, content_object=content_object,
                            expires=expires, args=args, kwargs=kwargs)
1195639
def schedule(identifier, **kwargs):
    ''''''
    source = actions.schedule(identifier, **kwargs)
    msg = 'Scheduled {source.name} with the following crontab: {cron}'
    log.info(msg.format(source=source, cron=source.periodic_task.crontab))
631398
private void appendToQueueInternal (final ScheduledJob job) {
		jobIdQueue.add(job.jobId());
		queuedJobs.put(job.jobId(), job);
	}
1011377
def move(self, dst):
        """"""
        shutil.move(self, dst)
        self = PathStr(dst).join(self.basename())
        return self
790042
def set_job(self, key, func, args):
        
        res, pk = key
        jobs, lock = self._jobs
        task = _tasks.UpdateTask(func(*args), key)
        with lock:
            job = jobs[res].get(pk)
            had = bool(job)
            if not job:
                job = task
                jobs[res][pk] = job
            else:
                task.cancel()
        self._log.debug('Scheduling: %s-%s (%s)', res.tag, pk,
                        'new task' if not had else 'dup')
        return job
730121
def put_calendar_job(self, calendar_id, job_id, params=None):
        
        for param in (calendar_id, job_id):
            if param in SKIP_IN_PATH:
                raise ValueError("Empty value passed for a required argument.")
        return self.transport.perform_request(
            "PUT",
            _make_path("_ml", "calendars", calendar_id, "jobs", job_id),
            params=params,
        )
1324725
def schedule(*args, &blk)
      return if blk.nil?
      @stop_mutex.synchronize do
        if @stopped
          GRPC.logger.warn('did not schedule job, already stopped')
          return
        end
        GRPC.logger.info('schedule another job')
        fail 'No worker threads available' if @ready_workers.empty?
        worker_queue = @ready_workers.pop

        fail 'worker already has a task waiting' unless worker_queue.empty?
        worker_queue << [blk, args]
      end
    end
848954
def cancel_job(self, job_id=None, job_name=None):
        
        payload = {}
        if job_name is not None:
            payload['job_name'] = job_name
        if job_id is not None:
            payload['job_id'] = job_id

        jobs_url = self._get_url('jobs_path')
        res = self.rest_client.session.delete(jobs_url, params=payload)
        _handle_http_errors(res)
        return res.json()
1332258
def schedule_batch(self, batch: Batch):
        
        jobs = list()
        for task, at, args, kwargs in batch.jobs_to_create:
            task = self._tasks.get(task)
            jobs.append(
                Job(task.name, task.queue, at, task.max_retries,
                    task_args=args, task_kwargs=kwargs)
            )
        return self._broker.enqueue_jobs(jobs)
1082121
def save_minions(jid, minions, syndic_id=None):
    '''
    
    '''
    # Ensure we have a list for Python 3 compatability
    minions = list(minions)

    log.debug(
        'Adding minions for job %s%s: %s',
        jid,
        ' from syndic master \'{0}\''.format(syndic_id) if syndic_id else '',
        minions
    )
    serial = salt.payload.Serial(__opts__)

    jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type'])

    try:
        if not os.path.exists(jid_dir):
            os.makedirs(jid_dir)
    except OSError as exc:
        if exc.errno == errno.EEXIST:
            # rarely, the directory can be already concurrently created between
            # the os.path.exists and the os.makedirs lines above
            pass
        else:
            raise

    if syndic_id is not None:
        minions_path = os.path.join(
            jid_dir,
            SYNDIC_MINIONS_P.format(syndic_id)
        )
    else:
        minions_path = os.path.join(jid_dir, MINIONS_P)

    try:
        if not os.path.exists(jid_dir):
            try:
                os.makedirs(jid_dir)
            except OSError:
                pass
        with salt.utils.files.fopen(minions_path, 'w+b') as wfh:
            serial.dump(minions, wfh)
    except IOError as exc:
        log.error(
            'Failed to write minion list %s to job cache file %s: %s',
            minions, minions_path, exc
        )
274243
def move(self, target):
        
        shutil.move(self.path, self._to_backend(target))
714731
def delay(name, args, kwargs):
    ''''''
    args = args or []
    kwargs = dict(k.split() for k in kwargs) if kwargs else {}
    if name not in celery.tasks:
        log.error('Job %s not found', name)
    job = celery.tasks[name]
    log.info('Sending job %s', name)
    async_result = job.delay(*args, **kwargs)
    log.info('Job %s sended to workers', async_result.id)
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
1136790
def run(self, jid=None):
        '''
        
        '''
        if self.opts.get('list_hosts'):
            self._get_roster()
            ret = {}
            for roster_file in self.__parsed_rosters:
                if roster_file.startswith('#'):
                    continue
                ret[roster_file] = {}
                for host_id in self.__parsed_rosters[roster_file]:
                    hostname = self.__parsed_rosters[roster_file][host_id]['host']
                    ret[roster_file][host_id] = hostname
            salt.output.display_output(ret, 'nested', self.opts)
            sys.exit()

        fstr = '{0}.prep_jid'.format(self.opts['master_job_cache'])
        jid = self.returners[fstr](passed_jid=jid or self.opts.get('jid', None))

        # Save the invocation information
        argv = self.opts['argv']

        if self.opts.get('raw_shell', False):
            fun = 'ssh._raw'
            args = argv
        else:
            fun = argv[0] if argv else ''
            args = argv[1:]

        job_load = {
            'jid': jid,
            'tgt_type': self.tgt_type,
            'tgt': self.opts['tgt'],
            'user': self.opts['user'],
            'fun': fun,
            'arg': args,
            }

        # save load to the master job cache
        try:
            if isinstance(jid, bytes):
                jid = jid.decode('utf-8')
            if self.opts['master_job_cache'] == 'local_cache':
                self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load, minions=self.targets.keys())
            else:
                self.returners['{0}.save_load'.format(self.opts['master_job_cache'])](jid, job_load)
        except Exception as exc:
            log.exception(exc)
            log.error(
                'Could not save load with returner %s: %s',
                self.opts['master_job_cache'], exc
            )

        if self.opts.get('verbose'):
            msg = 'Executing job with jid {0}'.format(jid)
            print(msg)
            print('-' * len(msg) + '\n')
            print('')
        sret = {}
        outputter = self.opts.get('output', 'nested')
        final_exit = 0
        for ret in self.handle_ssh():
            host = next(six.iterkeys(ret))
            if isinstance(ret[host], dict):
                host_ret = ret[host].get('retcode', 0)
                if host_ret != 0:
                    final_exit = 1
            else:
                # Error on host
                final_exit = 1

            self.cache_job(jid, host, ret[host], fun)
            ret = self.key_deploy(host, ret)

            if isinstance(ret[host], dict) and (ret[host].get('stderr') or '').startswith('ssh:'):
                ret[host] = ret[host]['stderr']

            if not isinstance(ret[host], dict):
                p_data = {host: ret[host]}
            elif 'return' not in ret[host]:
                p_data = ret
            else:
                outputter = ret[host].get('out', self.opts.get('output', 'nested'))
                p_data = {host: ret[host].get('return', {})}
            if self.opts.get('static'):
                sret.update(p_data)
            else:
                salt.output.display_output(
                        p_data,
                        outputter,
                        self.opts)
            if self.event:
                id_, data = next(six.iteritems(ret))
                if isinstance(data, six.text_type):
                    data = {'return': data}
                if 'id' not in data:
                    data['id'] = id_
                data['jid'] = jid  # make the jid in the payload the same as the jid in the tag
                self.event.fire_event(
                    data,
                    salt.utils.event.tagify(
                        [jid, 'ret', host],
                        'job'))
        if self.opts.get('static'):
            salt.output.display_output(
                    sret,
                    outputter,
                    self.opts)
        if final_exit:
            sys.exit(salt.defaults.exitcodes.EX_AGGREGATE)
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)
1317145
def change_execution_time(self, job, date_time):
        
        with self.connection.pipeline() as pipe:
            while 1:
                try:
                    pipe.watch(self.scheduled_jobs_key)
                    if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
                        raise ValueError('Job not in scheduled jobs queue')
                    pipe.zadd(self.scheduled_jobs_key, {job.id: to_unix(date_time)})
                    break
                except WatchError:
                    # If job is still in the queue, retry otherwise job is already executed
                    # so we raise an error
                    if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
                        raise ValueError('Job not in scheduled jobs queue')
                    continue