Comments (2)
Hi @christopherpickering
Thanks a lot for your hint. It's helped and now the code is working fine! Here's my version:
extenstions.py
:
from flask_apscheduler import APScheduler
from flask_apscheduler.auth import HTTPBasicAuth
import logging
from .. import api
def collect_master(master_hostname=None):
nbkt_check_api = api.NetbackupCheckApi()
logging.debug(f'Master {master_hostname} collection in progress')
nbkt_check_api.get_master_events(master_name=master_hostname, internal=True)
logging.debug('------------------------------------------------------')
scheduler = APScheduler()
scheduler.api_enabled = True
scheduler.auth = HTTPBasicAuth()
@scheduler.authenticate
def authenticate(auth):
"""Check auth."""
return auth["username"] == "guest" and auth["password"] == "guest"
Initializing from __init___.py
:
...
app = Flask(__name__)
app.config.from_object("config")
app.config['APP_NAME'] = app.config['APP_NAME']+" "+'.'.join(map(str,app.config['VERSION']))
db = SQLA(app)
migrate = Migrate(app, db)
appbuilder = AppBuilder(app, db.session, indexview=MyIndexView, base_template="mybase.html", security_manager_class=MySecurityManager, menu=Menu(extra_classes="navbar-fixed-top "))
from . import models, views, api# noqa
from .scheduler.extensions import scheduler, collect_master
scheduler.start()
# Add tasks to collect data from active masters
active_masters = db.session.query(models.MasterServer).filter_by(active=true()).all()
if active_masters is not None:
logging.debug(f"Active masters found: {active_masters}")
if app.config['SCHEDULER_DEFAULT_COLLECTION_INTERVAL'] >0:
for master in active_masters:
logging.debug(f"Starting scheduled job for: {master.hostname}, default collection interval: {app.config['SCHEDULER_DEFAULT_COLLECTION_INTERVAL']}")
with app.app_context():
job = scheduler.add_job(
trigger = 'interval',
id=f"{master.hostname}",
name = f"{master.hostname}",
seconds=app.config['SCHEDULER_DEFAULT_COLLECTION_INTERVAL'],
misfire_grace_time=900,
replace_existing=True,
func = collect_master,
args = [master.hostname],
)
And finally views.py
:
...
from .scheduler.extensions import scheduler, collect_master
...
def post_update(self, item):
super()
logging.debug(f"Currently scheduled jobs: [{scheduler.get_jobs()}]")
logging.debug(f"Is current item scheduled? [{scheduler.get_job(item.hostname)}]")
if not item.active and scheduler.get_job(item.hostname):
logging.debug(f"Master {item} is not active anymore, removing if from the scheduler")
scheduler.remove_job(item.hostname)
logging.debug(f"Currently scheduled jobs: [{scheduler.get_jobs()}]")
if item.active and scheduler.get_job(item.hostname) is None:
logging.debug(f"Master {item} is active now, adding it to the scheduler")
scheduler.add_job(
trigger = 'interval',
id=f"{item.hostname}",
name = f"{item.hostname}",
seconds=appbuilder.app.config['SCHEDULER_DEFAULT_COLLECTION_INTERVAL'],
misfire_grace_time=900,
replace_existing=True,
func = collect_master,
args = [item.hostname],
)
logging.debug(f"Currently scheduled jobs: [{scheduler.get_jobs()}]")
Thanks again and Happy New year :)
from flask-apscheduler.
I do something similar.. here's how I'm doing it:
- file called
extensions.py
where scheduler is initialized.. an also sqlachemy if you are using it.
from flask_apscheduler import APScheduler
from flask_sqlalchemy import SQLAlchemy # optional for sqlalchemy
from flask_sqlalchemy_caching import CachingQuery # for sqlalchemy
db = SQLAlchemy(query_class=CachingQuery) # for sqlalchemy
atlas_scheduler = APScheduler()
- then in
__init__.py
you can import it.
from scheduler.extensions import atlas_scheduler, db
...
# set it up inside you create_app()
db.init_app(app)
with app.app_context():
# pylint: disable=W0611
if atlas_scheduler.running is False:
# pytest imports twice. this will save us on the
# second import.
atlas_scheduler.start()
# here you should also add event listeners if you want them.
you can now import the scheduler from the extensions.py
wherever you want to use it. You will probably need to wrap w/ an app_context to make everything work.
Here's a link to my project: https://github.com/atlas-bi/atlas-automation-hub/tree/main/scheduler
from flask-apscheduler.
Related Issues (20)
- Flask-APScheduler not running when set some environment variables HOT 3
- Running job causes detachedinstanceerror HOT 3
- Use Codecov in informational mode HOT 1
- APScheduler not working with gunicorn eventlet HOT 6
- Flask 2.3.2 causing KeyError: 'JSONIFY_PRETTYPRINT_REGULAR' HOT 1
- Flask-APScheduler multiple jobs running at the same time when having multiple workers HOT 1
- [RFE] Package python3-flask-apscheduler into RPM
- KeyError: 'JSONIFY_PRETTYPRINT_REGULAR' when running Flask as a development server HOT 2
- Apscheduler not working with flask debug=True & --no-reload
- Flask 3.0.0 support HOT 1
- Behaviour of processpool HOT 1
- Key Error while passing redis instance as arg HOT 2
- Can't start BlockingScheduler as daemon in debug mode
- Issue with sqlalchemy (cannot join current thread and working outside of app context) HOT 4
- python3-flask-APScheduler_1.13.0.bb HOT 4
- Can I use hive database to restore jobs? HOT 2
- Coroutine as argument
- use api add task func which is not defined in the app start script failed HOT 2
- alembic migrations
- ModuleNotFoundError: No module named 'flask_apscheduler' HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from flask-apscheduler.