Create Celery beat schedule by get schedule from every installed app
177590
def create_celerybeat_schedule(apps):
    """"""
    beat_schedule = {}
    for app in apps:
        try:
            config = import_object_by_string(app)
            module = importlib.import_module('{}.cron'.format(config.name))
        except Exception:
            try:
                module = importlib.import_module('{}.cron'.format(app))
            except Exception:
                continue

        if not (hasattr(module, 'schedule') and isinstance(module.schedule, dict)):
            logger.warning('{} has no schedule or schedule is not a dict'.format(module.__name__))
            continue

        # Add cron queue option
        for name, schedule in module.schedule.items():
            options = schedule.get('options', {})
            if 'queue' not in options:
                options['queue'] = 'cron'
                schedule['options'] = options

                beat_schedule[name] = schedule

    return beat_schedule
1301601
function setup(done) {
    crontab.load(function(err, ct) {
      if (err) return done(err);
      clean(ct);
      load(ct);
      ct.save(done);
    });
  }
214333
def scheduling_block_instances(self):
        """"""
        # TODO(BMo) change this to a pipe?
        sbi_list = SchedulingBlockInstanceList()
        return json.dumps(dict(active=sbi_list.active,
                               completed=sbi_list.completed,
                               aborted=sbi_list.aborted))
825535
def schedule(self, seconds: float):
        
        def wrap(func: Callable):
            self._schedules.append(Scheduler(self.app, seconds, func))
        return wrap
753340
def patch_stackless():
    '''
    
    '''
    global _application_set_schedule_callback
    _application_set_schedule_callback = stackless.set_schedule_callback(_schedule_callback)

    def set_schedule_callback(callable):
        global _application_set_schedule_callback
        old = _application_set_schedule_callback
        _application_set_schedule_callback = callable
        return old

    def get_schedule_callback():
        global _application_set_schedule_callback
        return _application_set_schedule_callback

    set_schedule_callback.__doc__ = stackless.set_schedule_callback.__doc__
    if hasattr(stackless, "get_schedule_callback"):
        get_schedule_callback.__doc__ = stackless.get_schedule_callback.__doc__
    stackless.set_schedule_callback = set_schedule_callback
    stackless.get_schedule_callback = get_schedule_callback

    if not hasattr(stackless.tasklet, "trace_function"):
        # Older versions of Stackless, released before 2014
        __call__.__doc__ = stackless.tasklet.__call__.__doc__
        stackless.tasklet.__call__ = __call__

        setup.__doc__ = stackless.tasklet.setup.__doc__
        stackless.tasklet.setup = setup

        run.__doc__ = stackless.run.__doc__
        stackless.run = run
838299
def sources(scheduled=False):
    ''''''
    sources = actions.list_sources()
    if scheduled:
        sources = [s for s in sources if s.periodic_task]
    if sources:
        for source in sources:
            msg = '{source.name} ({source.backend}): {cron}'
            if source.periodic_task:
                cron = source.periodic_task.schedule_display
            else:
                cron = 'not scheduled'
            log.info(msg.format(source=source, cron=cron))
    elif scheduled:
        log.info('No sources scheduled yet')
    else:
        log.info('No sources defined yet')
1241102
def schedule_jobs(jobs)
      scheduler = Rufus::Scheduler.start_new

      jobs.each do |job|
        if job['cron']
          Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with cron:  #{job['cron']}")
          scheduler.cron job['cron'] do
            backup(job)
          end
        else
          scheduler.every job['interval'] do
            Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}")
            backup(job)
          end
        end
      end

      scheduler.join
    end
436719
def init_celery(self, celery):
        """"""

        count = next(self.counter)

        def task_with_hub(f, **opts):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                return f(self, *args, **kwargs)
            # Make sure newer instances don't overwride older ones.
            wrapper.__name__ = wrapper.__name__ + '_' + str(count)
            return celery.task(**opts)(wrapper)

        # tasks for internal use:
        self.subscribe = task_with_hub(subscribe)
        self.unsubscribe = task_with_hub(unsubscribe)

        max_attempts = self.config.get('MAX_ATTEMPTS', 10)
        make_req = task_with_hub(make_request_retrying, bind=True,
                                 max_retries=max_attempts)
        self.make_request_retrying = make_req

        # user facing tasks

        # wrapped by send_change_notification:
        self.send_change = task_with_hub(send_change_notification)

        # wrapped by cleanup_expired_subscriptions
        @task_with_hub
        def cleanup(hub):
            self.storage.cleanup_expired_subscriptions()
        self.cleanup = cleanup

        # wrapped by schedule_cleanup
        def schedule(every_x_seconds=A_DAY):
            celery.add_periodic_task(every_x_seconds,
                                     self.cleanup_expired_subscriptions.s())
        self.schedule = schedule
1123603
def schedule_tasks(self):
        
        url = 'api/v6/releases/%d/schedule-tasks' % self.id
        tasks = yield self.connection._get(url)
        defer.returnValue(munchify(tasks))
552912
def add_scheduling_block(config):
    """"""
    try:
        DB.add_sbi(config)
    except jsonschema.ValidationError as error:
        error_dict = error.__dict__
        for key in error_dict:
            error_dict[key] = error_dict[key].__str__()
        error_response = dict(message="Failed to add scheduling block",
                              reason="JSON validation error",
                              details=error_dict)
        return error_response, HTTPStatus.BAD_REQUEST
    response = dict(config=config,
                    message='Successfully registered scheduling block '
                            'instance with ID: {}'.format(config['id']))
    response['links'] = {
        'self': '{}scheduling-block/{}'.format(request.url_root,
                                               config['id']),
        'list': '{}'.format(request.url),
        'home': '{}'.format(request.url_root)
    }
    return response, HTTPStatus.ACCEPTED
264189
def cli(env, volume_id):
    """"""

    file_manager = SoftLayer.FileStorageManager(env.client)

    snapshot_schedules = file_manager.list_volume_schedules(volume_id)

    table = formatting.Table(['id',
                              'active',
                              'type',
                              'replication',
                              'date_created',
                              'minute',
                              'hour',
                              'day',
                              'week',
                              'day_of_week',
                              'date_of_month',
                              'month_of_year',
                              'maximum_snapshots'])

    for schedule in snapshot_schedules:

        if 'REPLICATION' in schedule['type']['keyname']:
            replication = '*'
        else:
            replication = formatting.blank()

        file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '')
        file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '')

        property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK',
                         'DAY_OF_WEEK', 'DAY_OF_MONTH',
                         'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT']

        schedule_properties = []
        for prop_key in property_list:
            item = formatting.blank()
            for schedule_property in schedule.get('properties', []):
                if schedule_property['type']['keyname'] == prop_key:
                    if schedule_property['value'] == '-1':
                        item = '*'
                    else:
                        item = schedule_property['value']
                    break
            schedule_properties.append(item)

        table_row = [
            schedule['id'],
            '*' if schedule.get('active', '') else '',
            file_schedule_type,
            replication,
            schedule.get('createDate', '')
        ]
        table_row.extend(schedule_properties)
        table.add_row(table_row)

    env.fout(table)
319439
def get_celery_info():
    
    import celery
    if not getattr(settings, 'USE_CELERY', False):
        log.error("No celery config found. Set USE_CELERY in settings to enable.")
        return {"status": NO_CONFIG}
    start = datetime.now()
    try:
        # pylint: disable=no-member
        app = celery.Celery('tasks')
        app.config_from_object('django.conf:settings', namespace='CELERY')
        # Make sure celery is connected with max_retries=1
        # and not the default of max_retries=None if the connection
        # is made lazily
        app.connection().ensure_connection(max_retries=1)

        celery_stats = celery.task.control.inspect().stats()
        if not celery_stats:
            log.error("No running Celery workers were found.")
            return {"status": DOWN, "message": "No running Celery workers"}
    except Exception as exp:  # pylint: disable=broad-except
        log.error("Error connecting to the backend: %s", exp)
        return {"status": DOWN, "message": "Error connecting to the backend"}
    return {"status": UP, "response_microseconds": (datetime.now() - start).microseconds}
158505
def app(config, src, dst, features, reload, force):
    """"""
    config = Path(config)
    if reload:
        argv = sys.argv.copy()
        argv.remove('--reload')
        monitor(config.dirname(), src, dst, argv)
    else:
        run(config, src, dst, force)
862952
def setup(cls, cron_cfg="cron"):
        
        random.seed()
        logging_cfg = cls.LOGGING_CFG
        if "%s" in logging_cfg:
            logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",)
        logging_cfg = os.path.expanduser(logging_cfg)

        if os.path.exists(logging_cfg):
            logging.HERE = os.path.dirname(logging_cfg)
            logging.config.fileConfig(logging_cfg)
        else:
            logging.basicConfig(level=logging.INFO)

        logging.getLogger().debug("Logging config read from '%s'" % logging_cfg)
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))
1271566
def celery_enable_all():
    """"""
    from celery.signals import task_prerun, task_postrun, task_failure
    task_prerun.connect(prerun_handler)
    task_postrun.connect(postrun_handler)
    # Also have to cleanup on failure.
    task_failure.connect(postrun_handler)
28136
def _run_apps(self, paths):
        

        for path in paths:
            common.shell_process(path, background=True)
            time.sleep(0.2)