The time intervals at which the workflow is to be extended are determined.
            .. code-block:: python

                #  request:
                   {
                   'task_inv_key': string,
                   }
517585
def select_postponed_date(self):
        

        _form = forms.JsonForm(title="Postponed Workflow")
        _form.start_date = fields.DateTime("Start Date")
        _form.finish_date = fields.DateTime("Finish Date")
        _form.save_button = fields.Button("Save")
        self.form_out(_form)
275443
def on_task_done(self, task):
        ''''''
        task['status'] = self.taskdb.SUCCESS
        task['lastcrawltime'] = time.time()

        if 'schedule' in task:
            if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
                task['status'] = self.taskdb.ACTIVE
                next_exetime = task['schedule'].get('age')
                task['schedule']['exetime'] = time.time() + next_exetime
                self.put_task(task)
            else:
                del task['schedule']
        self.update_task(task)

        project = task['project']
        self._cnt['5m'].event((project, 'success'), +1)
        self._cnt['1h'].event((project, 'success'), +1)
        self._cnt['1d'].event((project, 'success'), +1)
        self._cnt['all'].event((project, 'success'), +1).event((project, 'pending'), -1)
        logger.info('task done %(project)s:%(taskid)s %(url)s', task)
        return task
929375
def get_accessible_time(self, plugin_override=True):
        
        vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible)
        return vals[0] if len(vals) and plugin_override else self._accessible
234947
def calculate_file_access_time(workflow_workspace):
    """"""
    access_times = {}
    for subdir, dirs, files in os.walk(workflow_workspace):
        for file in files:
            file_path = os.path.join(subdir, file)
            access_times[file_path] = os.stat(file_path).st_atime
    return access_times
1251681
def perform(task_params, scheduled_time)
      @task = Task.new(task_params)
      @scheduled_time = Time.at(scheduled_time).in_time_zone(@task.time_zone)
      raise Expired if expired?

      queue_task
    end
362769
def CreateTaskCompletion(self):
    
    self.completion_time = int(
        time.time() * definitions.MICROSECONDS_PER_SECOND)

    task_completion = TaskCompletion()
    task_completion.aborted = self.aborted
    task_completion.identifier = self.identifier
    task_completion.session_identifier = self.session_identifier
    task_completion.timestamp = self.completion_time
    return task_completion
592745
def _hash_task(task):
    

    params = task.get("params")
    if params:
        params = json.dumps(sorted(list(task["params"].items()), key=lambda x: x[0]))  # pylint: disable=no-member

    full = [str(task.get(x)) for x in ["path", "interval", "dailytime", "weekday", "monthday", "queue"]]

    full.extend([str(params)])
    return " ".join(full)
291618
def clock_in(request):
    """"""
    user = request.user
    # Lock the active entry for the duration of this transaction, to prevent
    # creating multiple active entries.
    active_entry = utils.get_active_entry(user, select_for_update=True)

    initial = dict([(k, v) for k, v in request.GET.items()])
    data = request.POST or None
    form = ClockInForm(data, initial=initial, user=user, active=active_entry)
    if form.is_valid():
        entry = form.save()
        message = 'You have clocked into {0} on {1}.'.format(
            entry.activity.name, entry.project)
        messages.info(request, message)
        return HttpResponseRedirect(reverse('dashboard'))

    return render(request, 'timepiece/entry/clock_in.html', {
        'form': form,
        'active': active_entry,
    })
255111
private String getScheduling(TaskType value)
   {
      String result = "fixed-work";
      if (value != null && value == TaskType.FIXED_DURATION)
      {
         result = "fixed-duration";
      }
      return (result);
   }
433291
def _check_select(self):
        
        if not self.interactive:
            return super(OneScheduler, self)._check_select()

        # waiting for running tasks
        if self.running_task > 0:
            return

        is_crawled = []

        def run(project=None):
            return crawl('on_start', project=project)

        def crawl(url, project=None, **kwargs):
            """
            Crawl given url, same parameters as BaseHandler.crawl

            url - url or taskid, parameters will be used if in taskdb
            project - can be ignored if only one project exists.
            """

            # looking up the project instance
            if project is None:
                if len(self.projects) == 1:
                    project = list(self.projects.keys())[0]
                else:
                    raise LookupError('You need specify the project: %r'
                                      % list(self.projects.keys()))
            project_data = self.processor.project_manager.get(project)
            if not project_data:
                raise LookupError('no such project: %s' % project)

            # get task package
            instance = project_data['instance']
            instance._reset()
            task = instance.crawl(url, **kwargs)
            if isinstance(task, list):
                raise Exception('url list is not allowed in interactive mode')

            # check task in taskdb
            if not kwargs:
                dbtask = self.taskdb.get_task(task['project'], task['taskid'],
                                              fields=self.request_task_fields)
                if not dbtask:
                    dbtask = self.taskdb.get_task(task['project'], task['url'],
                                                  fields=self.request_task_fields)
                if dbtask:
                    task = dbtask

            # select the task
            self.on_select_task(task)
            is_crawled.append(True)

            shell.ask_exit()

        def quit_interactive():
            '''Quit interactive mode'''
            is_crawled.append(True)
            self.interactive = False
            shell.ask_exit()

        def quit_pyspider():
            '''Close pyspider'''
            is_crawled[:] = []
            shell.ask_exit()

        shell = utils.get_python_console()
        banner = (
            'pyspider shell - Select task\n'
            'crawl(url, project=None, **kwargs) - same parameters as BaseHandler.crawl\n'
            'quit_interactive() - Quit interactive mode\n'
            'quit_pyspider() - Close pyspider'
        )
        if hasattr(shell, 'show_banner'):
            shell.show_banner(banner)
            shell.interact()
        else:
            shell.interact(banner)
        if not is_crawled:
            self.ioloop.add_callback(self.ioloop.stop)
758828
static function getWorkflowState($workflow_key) {
        $status = self::STATUS_COMPLETED;
        $created_after = "-20 years";
        $data = DataStore::retrieveMostCurrentWorkflowJobByAgeAndStatus($workflow_key, $status, $created_after);
        if ($data) {
            return $data["end_state"];
        } else {
            $workflow = DataStore::retrieveWorkflow($workflow_key);
            if (!$workflow) {
                throw new \Exception("Error retrieving workflow for key $workflow_key can't determine state.");
            }
            $data = $workflow->getData();
            return $data[self::CONF_INITIAL_STATE];
        }
    }
1367873
def for_each_time_range(t)
      RedisAnalytics.redis_key_timestamps.map{|x, y| t.strftime(x)}.each do |ts|
        yield(ts)
      end
    end
129350
def _execute_workflow(cls, process_args):
        
        workflow, input_args, log_path = process_args

        if log_path:
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)
            handler = cls._get_log_handler(log_path)
            logger.addHandler(handler)

        stats = {'start_time': dt.datetime.now()}
        try:
            _ = workflow.execute(input_args, monitor=True)
        except BaseException:
            stats['error'] = traceback.format_exc()
        stats['end_time'] = dt.datetime.now()

        if log_path:
            handler.close()
            logger.removeHandler(handler)

        return stats
843079
def idle_task(self):
        ''''''
        now = time.time()
        time_delta = now - self.last_calc
        if time_delta > 1:
            self.last_calc = now
            self.buckets.append(self.counts)
            self.counts = {}
            if len(self.buckets) > self.max_buckets:
                self.buckets = self.buckets[-self.max_buckets:]
1096171
static function runFromKey($workflow_key) {
        $workflow_job_config = [];
        $start_time = microtime(true);
        /**
         * First doing a simple setup... does this work?
         * Nothing get saved at this point errors here is most likely to be
         * a runtime problem. Like locking errorous jobs or that a job is already running.
         */
        try {
            $workflow_config = self::getWorkflowConfig($workflow_key);
            $workflow_job_key = self::createWorkflowJobKey();
            $workflow_job_config = self::createJobConfig($workflow_config);
            $start_state = self::getWorkflowState($workflow_key);
            $workflow_job_config = self::startJob($workflow_job_key, $workflow_job_config, $start_state);
        } catch (\Exception $exception) {
            syslog(LOG_ERR, $exception->getMessage());
            $workflow_job_config["status"] = self::STATUS_ERROR;
            $workflow_job_config["message"] = "Got this error: " . $exception->getMessage();
            $workflow_job_config["runtime"] = microtime(true) - $start_time;
            return $workflow_job_config;
        }
        /**
         * Continues with a working setup and trying to do the config run.
         */
        try {
            ob_start();
            $end_state = self::runFromConfig($workflow_config, $start_state);
            $workflow_job_config["message"] = ob_get_clean();
            $workflow_job_config["runtime"] = microtime(true) - $start_time;
            if ($end_state) {
                return self::endJob($workflow_job_key, $workflow_job_config, $end_state);
            } else {
                return self::failJob($workflow_job_key, $workflow_job_config, "Job didn't emit an endstate.");
            }
        } catch (\Exception $exception) {
            $workflow_job_config["runtime"] = microtime(true) - $start_time;
            return self::failJob($workflow_job_key, $workflow_job_config, $exception->getMessage());
        }
    }
259049
def taskinfo(self):
        

        task_input = {'taskName': 'QueryTask',
                      'inputParameters': {"Task_Name": self._name}}

        info = taskengine.execute(task_input, self._engine, cwd=self._cwd)

        task_def = info['outputParameters']['DEFINITION']

        task_def['name'] = str(task_def.pop('NAME'))
        task_def['description'] = str(task_def.pop('DESCRIPTION'))
        task_def['displayName'] = str(task_def.pop('DISPLAY_NAME'))

        if 'COMMUTE_ON_SUBSET' in task_def:
            task_def['commute_on_subset'] = task_def.pop('COMMUTE_ON_SUBSET')
        if 'COMMUTE_ON_DOWNSAMPLE' in task_def:
            task_def['commute_on_downsample'] = task_def.pop('COMMUTE_ON_DOWNSAMPLE')

        # Convert PARAMETERS into a list instead of a dictionary
        # which matches the gsf side things
        task_def['parameters'] = \
            [v for v in task_def['PARAMETERS'].values()]
        task_def.pop('PARAMETERS')

        parameters = task_def['parameters']
        for parameter in parameters:
            parameter['name'] = str(parameter.pop('NAME'))
            parameter['description'] = str(parameter.pop('DESCRIPTION'))
            parameter['display_name'] = str(parameter.pop('DISPLAY_NAME'))
            parameter['required'] = bool(parameter.pop('REQUIRED'))

            if 'MIN' in parameter:
                parameter['min'] = parameter.pop('MIN')

            if 'MAX' in parameter:
                parameter['max'] = parameter.pop('MAX')

            if parameter['TYPE'].count('['):
                parameter['type'], parameter['dimensions'] = parameter.pop('TYPE').split('[')
                parameter['dimensions'] = '[' + parameter['dimensions']
                parameter['type'] = str(parameter['type'])
            else:
                parameter['type'] = str(parameter.pop('TYPE').split('ARRAY')[0])

            if 'DIMENSIONS' in parameter:
                parameter['dimensions'] = parameter.pop('DIMENSIONS')

            if 'DIRECTION' in parameter:
                parameter['direction'] = parameter.pop('DIRECTION').lower()

            if 'DEFAULT' in parameter:
                if parameter['DEFAULT'] is not None:
                    parameter['default_value'] = parameter.pop('DEFAULT')
                else:
                    parameter.pop('DEFAULT')

            if 'CHOICE_LIST' in parameter:
                if parameter['CHOICE_LIST'] is not None:
                    parameter['choice_list'] = parameter.pop('CHOICE_LIST')
                else:
                    parameter.pop('CHOICE_LIST')

            if 'FOLD_CASE' in parameter:
                parameter['fold_case'] = parameter.pop('FOLD_CASE')

            if 'AUTO_EXTENSION' in parameter:
                parameter['auto_extension'] = parameter.pop('AUTO_EXTENSION')

            if 'IS_TEMPORARY' in parameter:
                parameter['is_temporary'] = parameter.pop('IS_TEMPORARY')

            if 'IS_DIRECTORY' in parameter:
                parameter['is_directory'] = parameter.pop('IS_DIRECTORY')

        return task_def
1130016
def check_for_stalled_tasks():
    
    from api.models.tasks import Task
    for task in Task.objects.filter(status_is_running=True):
        if not task.is_responsive():
            task.system_error()
        if task.is_timed_out():
            task.timeout_error()