<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:

def setup_scheduler(self, before_connect=False):
        '''
        Set up the scheduler.
        This is safe to call multiple times.
        '''
        self._setup_core()

        loop_interval = self.opts['loop_interval']
        new_periodic_callbacks = {}

        if 'schedule' not in self.periodic_callbacks:
            if 'schedule' not in self.opts:
                self.opts['schedule'] = {}
            if not hasattr(self, 'schedule'):
                self.schedule = salt.utils.schedule.Schedule(
                    self.opts,
                    self.functions,
                    self.returners,
                    utils=self.utils,
                    cleanup=[master_event(type='alive')])

            try:
                if self.opts['grains_refresh_every']:  # In minutes, not seconds!
                    log.debug(
                        'Enabling the grains refresher. Will run every %d minute(s).',
                        self.opts['grains_refresh_every']
                    )
                    self._refresh_grains_watcher(abs(self.opts['grains_refresh_every']))
            except Exception as exc:
                log.error(
                    'Exception occurred in attempt to initialize grain refresh '
                    'routine during minion tune-in: %s', exc
                )

            # TODO: actually listen to the return and change period
            def handle_schedule():
                self.process_schedule(self, loop_interval)
            new_periodic_callbacks['schedule'] = tornado.ioloop.PeriodicCallback(handle_schedule, 1000)

            if before_connect:
                # Make sure there is a chance for one iteration to occur before connect
                handle_schedule()

        if 'cleanup' not in self.periodic_callbacks:
            new_periodic_callbacks['cleanup'] = tornado.ioloop.PeriodicCallback(
                    self._fallback_cleanups, loop_interval * 1000)

        # start all the other callbacks
        for periodic_cb in six.itervalues(new_periodic_callbacks):
            periodic_cb.start()

        self.periodic_callbacks.update(new_periodic_callbacks)