# Buggy code
def setup_scheduler(manager):
    """Configure and start apscheduler"""
    global scheduler
    if logging.getLogger().getEffectiveLevel() > logging.DEBUG:
        logging.getLogger("apscheduler").setLevel(logging.WARNING)
    jobstores = {
        "default": SQLAlchemyJobStore(engine=manager.engine, metadata=Base.metadata)
    }
    # If job was meant to run within last day while daemon was shutdown, run it once when continuing
    job_defaults = {"coalesce": True, "misfire_grace_time": 60 * 60 * 24}
    try:
        timezone = tzlocal.get_localzone()
        if timezone.zone == "local":
            timezone = None
    except pytz.UnknownTimeZoneError:
        timezone = None
    except struct.error as e:
        # Hiding exception that may occur in tzfile.py seen in entware
        log.warning("Hiding exception from tzlocal: %s", e)
        timezone = None
    if not timezone:
        # The default sqlalchemy jobstore does not work when there isn't a name for the local timezone.
        # Just fall back to utc in this case
        # FlexGet #2741, upstream ticket https://github.com/agronholm/apscheduler/issues/59
        log.info(
            "Local timezone name could not be determined. Scheduler will display times in UTC for any log"
            "messages. To resolve this set up /etc/timezone with correct time zone name."
        )
        timezone = pytz.utc
    scheduler = BackgroundScheduler(
        jobstores=jobstores, job_defaults=job_defaults, timezone=timezone
    )
    setup_jobs(manager)


# Traceback (OperationalError)
2016-08-26 12:17 INFO     db_analyze    task    Running ANALYZE on database to improve performance.
2016-08-26 12:19 WARNING  apscheduler.scheduler                 Execution of job "* (trigger: interval[1:00:00], next run at: 2016-08-26 12:19:02 EEST)" skipped: maximum number of running instances reached (1)
Exception in thread APScheduler:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/apscheduler/schedulers/blocking.py", line 30, in _main_loop
wait_seconds = self._process_jobs()
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/apscheduler/schedulers/base.py", line 960, in _process_jobs
jobstore.update_job(job)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/apscheduler/jobstores/sqlalchemy.py", line 101, in update_job
result = self.engine.execute(update)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1991, in execute
return connection.execute(statement, *multiparams, **params)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1146, in _execute_context
context)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
exc_info
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
context)
File "/home/xxx/apps/flexget/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute
cursor.execute(statement, parameters)
OperationalError: (sqlite3.OperationalError) database is locked [SQL: u'UPDATE apscheduler_jobs SET next_run_time=?, job_state=? WHERE apscheduler_jobs.id = ?'] [parameters: (1472206742.394899, <read-only buffer for 0x7fd6b4014be0, size -1, offset 0 at 0x7fd6a85a5ef0>, '4b7429f83440f1967e4c5e82c357e52d4911ee88')]

# Fixed code
def setup_scheduler(manager):
    """Configure and start apscheduler"""
    global scheduler
    if logging.getLogger().getEffectiveLevel() > logging.DEBUG:
        logging.getLogger("apscheduler").setLevel(logging.WARNING)
    # Since APScheduler runs in a separate thread, slower devices can sometimes get a DB lock, so use a separate db
    # for the jobs to avoid this
    db_filename = os.path.join(
        manager.config_base, "db-%s-jobs.sqlite" % manager.config_name
    )
    # in case running on windows, needs double \\
    db_filename = db_filename.replace("\\", "\\\\")
    database_uri = "sqlite:///%s" % db_filename
    jobstores = {"default": SQLAlchemyJobStore(url=database_uri)}
    # If job was meant to run within last day while daemon was shutdown, run it once when continuing
    job_defaults = {"coalesce": True, "misfire_grace_time": 60 * 60 * 24}
    try:
        timezone = tzlocal.get_localzone()
        if timezone.zone == "local":
            timezone = None
    except pytz.UnknownTimeZoneError:
        timezone = None
    except struct.error as e:
        # Hiding exception that may occur in tzfile.py seen in entware
        log.warning("Hiding exception from tzlocal: %s", e)
        timezone = None
    if not timezone:
        # The default sqlalchemy jobstore does not work when there isn't a name for the local timezone.
        # Just fall back to utc in this case
        # FlexGet #2741, upstream ticket https://github.com/agronholm/apscheduler/issues/59
        log.info(
            "Local timezone name could not be determined. Scheduler will display times in UTC for any log"
            "messages. To resolve this set up /etc/timezone with correct time zone name."
        )
        timezone = pytz.utc
    scheduler = BackgroundScheduler(
        jobstores=jobstores, job_defaults=job_defaults, timezone=timezone
    )
    setup_jobs(manager)