How to use the apscheduler.scheduler.Scheduler function in APScheduler

To help you get started, we’ve selected a few APScheduler examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rasathus / circadianLighting / app.py View on Github external
args = parser.parse_args()
    if args.driver_type is not None and args.led_count is not None:
        if args.driver_type.lower() in valid_led_drivers:
            app.logger.info("LED Driver is :%s with %d in the chain" % (args.driver_type, args.led_count))
            led_chain = Chain_Communicator(driver_type=args.driver_type.lower(), chain_length=args.led_count)
        else:
            raise Exception("Invalid LED Driver %s specified, implemented types are : %s" % (args.driver_type, valid_led_drivers))
    else:
        try:
            led_chain = Chain_Communicator(driver_type=app_config.get("chain", "type"), chain_length=int(app_config.get("chain", "length")))
        except ConfigParser.NoOptionError:
            app.logger.warning("Unable to find both length and type properties in chain section of configuration file.")


    sched = Scheduler()
    sched.start()
    # calculate our events from the auto_state_events list, need to find a better way of doing this, maybe a config file.
    for event in auto_state_events:
        app.logger.info("Processing scheduled event : %s" % event['event_name'])
        start_hour = event['event_start_time'].split(':')[0]
        start_minute = event['event_start_time'].split(':')[1]
        start_second = event['event_start_time'].split(':')[2]
        start_time = datetime.strptime(event['event_start_time'],time_format)
        end_time = datetime.strptime(event['event_end_time'],time_format)
        event_duration = (end_time - start_time).seconds 
        sched.add_cron_job(led_chain.auto_transition, hour=start_hour, minute=start_minute, second=start_second , name=event['event_name'], kwargs={'state' : event['event_state'], 'transition_duration' : event['transition_duration']}, misfire_grace_time=event_duration)

    app.logger.debug("Startup job list contains : %s" % sched.get_jobs())

    try:
        app.run(host='0.0.0.0', port=int(app_config.get("general", "web_port")), use_reloader=False)
github IBM-Cloud / todo-apps / python / mongo-app.py View on Github external
#Only find the services with the name todo-mongo-db, there should only be one
        mongoServices = filter(lambda s: s['name'] == 'todo-mongo-db', value)
        if len(mongoServices) != 0:
            mongoService = mongoServices[0]
            if "uri" in mongoService['credentials']:
                url = mongoService['credentials']['uri']
            else:
                url = mongoService['credentials']['url']


client = MongoClient(url)
db = client.get_default_database()
collection = db.todos

# Create a scheduled task that will cleanup ToDos if the list grows too big
sched = Scheduler()
sched.start()
def cleanup():
    if collection.count() > 20:
        collection.remove(collection.find_one())
sched.add_interval_job(cleanup, seconds=30)

# Serve up index.html when requests come to root
@app.route('/')
def index():
    return app.send_static_file('index.html')

# Serve up static resources, JavaScript, HTML, CSS
@app.route('/')
def js_proxy(path):
    # send_static_file will guess the correct MIME type
    return app.send_static_file(os.path.join(path))
github domogik / domogik / src / domogik / xpl / lib / dawndusk.py View on Github external
def __init__(self,lgt,lat,use_cron,myxpl,log):
        """
        Init the dawndusk API
        @param lgt : longitude of the observer
        @param lat : latitude of the observer
        """
        self.use_cron = use_cron
        self.log = log
        self.myxpl = myxpl
        if self.use_cron == False:
            self._scheduler = Scheduler()
            self._scheduler.start()
        else:
            self._cronQuery = cronQuery(self.myxpl,self.log)
        self.mycity = ephem.Observer()
        self.mycity.lat, self.mycity.lon = lat, lgt
        self.mycity.horizon = '-6'
github domogik / domogik / src / domogik_packages / xpl / lib / cron.py View on Github external
def __init__(self, api):
        """
        Init the cronjobs container

        @param api:

        """
        self.data = dict()
        self._api = api
        self._scheduler = Scheduler()
        self.store = CronStore(self._api.log, self._api.data_files_dir)
        self._scheduler.start()
        self._jobs_lock = threading.Semaphore()
        self.store.load_all(self.add_job)
        self._api.log.info("Load %s jobs from store." % len(self.data))
github materialsproject / pymatgen / pymatgen / io / abinit / launcher.py View on Github external
self.customer_service_dir = Directory(self.customer_service_dir)
            self._validate_customer_service()

        if kwargs:
            raise self.Error("Unknown arguments %s" % kwargs)

        if not has_apscheduler:
            raise RuntimeError("Install apscheduler with pip")

        if has_sched_v3:
            logger.warning("Using scheduler v>=3.0.0")
            from apscheduler.schedulers.blocking import BlockingScheduler
            self.sched = BlockingScheduler()
        else:
            from apscheduler.scheduler import Scheduler
            self.sched = Scheduler(standalone=True)

        self.nlaunch = 0
        self.num_reminders = 1

        # Used to keep track of the exceptions raised while the scheduler is running
        self.exceptions = deque(maxlen=self.max_num_pyexcs + 10)

        # Used to push additional info during the execution.
        self.history = deque(maxlen=100)
github simplecrypto / simplecoin_multi / simplecoin / __init__.py View on Github external
app.config['hash'] = ''
            app.config['revdate'] = ''

        app.logger.info("Starting up SimpleCoin!\n{}".format("=" * 100))

    # Configure app for running scheduler.py functions + instantiate scheduler
    # =======================================================================
    elif mode == "scheduler":
        if sentry and 'SENTRY_NAME' in app.config:
            app.config['SENTRY_NAME'] = app.config['SENTRY_NAME'] + "_scheduler"

        app.logger.info("=" * 80)
        app.logger.info("SimpleCoin cron scheduler starting up...")
        setproctitle.setproctitle("simplecoin_scheduler")

        sched = Scheduler(standalone=True)

        # monkey patch the scheduler to wrap each job call in its own flask
        # context. Kind of sloppy way to pass in the app context...
        Scheduler.app = app
        Scheduler._old_run_job = Scheduler._run_job

        def _run_job(self, *args, **kwargs):
            with self.app.app_context():
                Scheduler._old_run_job(self, *args, **kwargs)
        Scheduler._run_job = _run_job

        stage_tasks = set(["cache_profitability", "leaderboard",
                           "server_status", "update_network",
                           "cache_user_donation", "update_online_workers"])
        for task_config in app.config['tasks']:
            if not task_config.get('enabled', False):
github rembo10 / headphones / threadtools.py View on Github external
from cherrypy.process.plugins import SimplePlugin
from apscheduler.scheduler import Scheduler

import os
import time
import threading
import Queue

class threadtool(SimplePlugin):

	sched = Scheduler()
	thread = None

	def __init__(self, bus):
		SimplePlugin.__init__(self, bus)
			
	def start(self):
		self.running = True
		if not self.thread:
			self.thread = threading.Thread(target=self.run)
			self.thread.start()
		self.sched.start()
	start.priority = 80
		
	def stop(self):
		self.running = False
		if self.thread:
github nextgis / nextgiscrowd / ngcrowd / __init__.py View on Github external
def start_scheduler():
    scheduler = Scheduler()
    scheduler.start()
    start_export()
    scheduler.add_cron_job(start_export, month='*', day='*', hour='16')