示例#1
0
def test6():
    """定时执行任务,暂停,恢复, 实例化"""
    start_time = time.time()
    scheduler = BackgroundScheduler()
    job = scheduler.add_job(my_job, 'interval', args=('123',),seconds=1, id='my_job_id') # 每隔1秒执行一次my_job函数,args为函数my_job的输入参数;id:可省略;
    print("作业id:{},作业名字:{},作业参数:{},作业函数:{},触发条件:{}".format(job.id, job.name, job.args, job.func,  job.trigger))
    scheduler.start() # 程序运行到这里,任务没有运行完也会往后执行,既执行后面的任务,又执行这个任务。
    print('运行到了这里1')
    while (scheduler.state):
        if time.time() - start_time >5:
            print('暂停作业')
            #scheduler.pause() # 暂停作业:
            job.pause() # 暂停单个实例
            break
    print('恢复作业')
    if time.time() - start_time >5:
        #scheduler.resume() # 恢复作业
        job.resume() # 恢复单个实例
    time.sleep(4)
    print('当前任务列表:{}'.format(scheduler.get_jobs())) # 获得调度作业的列表,可以使用 get_jobs() 来完成,它会返回所有的job实例
    scheduler.get_job('my_job_id') # 获取id为my_job_id的作业实例
    
    scheduler.print_jobs() # 输出所有格式化的作业列表。
    
    print('移除作业')
    # scheduler.remove_job('my_job_id') # 移除id为my_job_id的作业
    # scheduler.remove_all_jobs() # 移除所有的作业
    job.remove() # 移除单个实例的作业
def startpoll():
    # autopolling()
    scheduler = BackgroundScheduler(timezone='America/Los_Angeles')
    scheduler.start()
    scheduler.add_job(func=autopolling, trigger="interval", seconds=1800)
    scheduler.add_job(func=dockercheck, trigger="interval", seconds=60)
    scheduler.print_jobs()
def test6():
    """定时执行任务,暂停,恢复, 实例化"""
    start_time = time.time()
    scheduler = BackgroundScheduler()
    job = scheduler.add_job(
        my_job, 'interval', args=('123', ), seconds=1,
        id='my_job_id')  # 每隔1秒执行一次my_job函数,args为函数my_job的输入参数;id:可省略;
    print("作业id:{},作业名字:{},作业参数:{},作业函数:{},触发条件:{}".format(
        job.id, job.name, job.args, job.func, job.trigger))
    scheduler.start()  # 程序运行到这里,任务没有运行完也会往后执行,既执行后面的任务,又执行这个任务。
    print('运行到了这里1')
    while (scheduler.state):
        if time.time() - start_time > 5:
            print('暂停作业')
            #scheduler.pause() # 暂停作业:
            job.pause()  # 暂停单个实例
            break
    print('恢复作业')
    if time.time() - start_time > 5:
        #scheduler.resume() # 恢复作业
        job.resume()  # 恢复单个实例
    time.sleep(4)
    print('当前任务列表:{}'.format(
        scheduler.get_jobs()))  # 获得调度作业的列表,可以使用 get_jobs() 来完成,它会返回所有的job实例
    scheduler.get_job('my_job_id')  # 获取id为my_job_id的作业实例

    scheduler.print_jobs()  # 输出所有格式化的作业列表。

    print('移除作业')
    # scheduler.remove_job('my_job_id') # 移除id为my_job_id的作业
    # scheduler.remove_all_jobs() # 移除所有的作业
    job.remove()  # 移除单个实例的作业
def init_season():

    Dday, Dmonth, Dyear, dict_Dates = parse_dates()

    scheduler = BackgroundScheduler()
    scheduler.add_job(new_season,
                      'date',
                      run_date=date(Dyear[1], Dmonth[1], Dday[1]),
                      args=[1],
                      id="S1")
    scheduler.add_job(new_season,
                      'date',
                      run_date=date(Dyear[2], Dmonth[2], Dday[2]),
                      args=[2],
                      id="S2")
    scheduler.add_job(new_season,
                      'date',
                      run_date=date(Dyear[3], Dmonth[3], Dday[3]),
                      args=[3],
                      id="S3")
    scheduler.add_job(new_season,
                      'date',
                      run_date=date(Dyear[4], Dmonth[4], Dday[4]),
                      args=[4],
                      id="S4")
    # scheduler.add_job(new_season, 'date', run_date=datetime(Dyear[1], Dmonth[1], Dday[1], 1, 58, 5), args=[1], id="S1")
    # scheduler.add_job(new_season, 'date', run_date=datetime(Dyear[2], Dmonth[2], Dday[2], 2, 13, 5), args=[2], id="S2")
    # scheduler.add_job(new_season, 'date', run_date=datetime(Dyear[3], Dmonth[3], Dday[3], 2, 14, 5), args=[3], id="S3")
    # scheduler.add_job(new_season, 'date', run_date=datetime(Dyear[4], Dmonth[4], Dday[4], 2, 15, 5), args=[4], id="S4")
    #scheduler.add_job(new_season, 'interval', seconds=70, args=[1], id="S1")

    scheduler.start()

    scheduler.print_jobs()
示例#5
0
def initialize_scheduler(system_map):

    scheduler = BackgroundScheduler(jobstores=jobstores,
                                    executors=executors,
                                    job_defaults=job_defaults)
    scheduler.add_job(minutely,
                      'interval',
                      minutes=1,
                      id='every minute',
                      replace_existing=True,
                      args=[system_map])
    scheduler.add_job(quarter_hourly,
                      'interval',
                      minutes=15,
                      id='every 15 minutes',
                      replace_existing=True,
                      args=[system_map])
    scheduler.add_job(hourly,
                      'interval',
                      minutes=60,
                      id='every hour',
                      replace_existing=True,
                      args=[system_map])
    scheduler.add_job(daily,
                      'cron',
                      day='*',
                      hour='2',
                      id='every day at 2am',
                      replace_existing=True,
                      args=[system_map])
    scheduler.start()
    scheduler.print_jobs()
    print('generator will sleep now, while tasks run in the background')
    return scheduler
def test3():
    """定时执行任务,暂停,恢复"""
    start_time = time.time()
    scheduler = BackgroundScheduler()
    scheduler.add_job(
        my_job, 'interval', args=('123', ), seconds=1,
        id='my_job_id')  # 每隔1秒执行一次my_job函数,args为函数my_job的输入参数;id:可省略;
    scheduler.start()  # 程序运行到这里,任务没有运行完也会往后执行,既执行后面的任务,又执行这个任务。
    print('运行到了这里1')
    while (scheduler.state):
        if time.time() - start_time > 5:
            print('暂停作业')
            scheduler.pause()  # 暂停作业:
            break
    print('恢复作业')
    if time.time() - start_time > 5:
        scheduler.resume()  #
    time.sleep(4)
    print('当前任务列表:{}'.format(
        scheduler.get_jobs()))  # 获得调度作业的列表,可以使用 get_jobs() 来完成,它会返回所有的job实例
    scheduler.get_job('my_job_id')  # 获取id为my_job_id的作业实例

    scheduler.print_jobs()  # 输出所有格式化的作业列表。

    print('移除作业')
    # scheduler.remove_job('my_job_id') # 移除id为my_job_id的作业
    scheduler.remove_all_jobs()  # 移除所有的作业
示例#7
0
def setup_cron(function):
    """Set up the cron job run my AP Scheduler"""
    sched = BackgroundScheduler()
    sched.add_job(function,
                  'interval',
                  hours=1,
                  timezone=pytz.timezone('US/Eastern'))
    sched.add_job(set_last_time_run,
                  'interval',
                  hours=1,
                  timezone=pytz.timezone('US/Eastern'))
    sched.start()
    sched.print_jobs()
示例#8
0
    def add_tasks():
        #scheduler = BlockingScheduler()
        scheduler = BackgroundScheduler()
        # scheduler.add_job(reminder_ins.checkForReminders, 'interval', seconds=30)
        scheduler.add_job(reminder_ins.checkForReminders2, 'interval', seconds=30)
        print('api: Press Ctrl+{0} to exit scheduler'.format('Break' if os.name == 'nt' else 'C'))
        try:
            scheduler.start()

        except (KeyboardInterrupt, SystemExit):
            pass
        scheduler.print_jobs()
        atexit.register(lambda: scheduler.shutdown())
示例#9
0
def main(argv):
    try:
        # ensure single instance process
        me = tendo_singleton.SingleInstance()

        # set high priority
        # os.nice(-20)
        # os.setpriority(os.PRIO_PROCESS, 0, -20)
        # import psutil
        # p = psutil.Process()
        # p.ionice(0)

        logging.info("Started")

        loop = asyncio.get_event_loop()

        # https://stackoverflow.com/questions/2720319/python-figure-out-local-timezone
        local_tz_str = datetime.datetime.now(
            datetime.timezone.utc).astimezone().tzinfo.tzname(
                datetime.datetime.now())
        logging.info("TZ: " + local_tz_str)
        #scheduler = BackgroundScheduler(timezone=local_tz_str, standalone=False, job_defaults={'misfire_grace_time': 60 * 60}, )
        scheduler = BackgroundScheduler(
            timezone=None,
            standalone=False,
            job_defaults={'misfire_grace_time': 60 * 60},
        )
        scheduler.add_job(
            set_tv_source, 'cron',
            minute=0)  # Turn the TV on/off, and set the TV source
        scheduler.add_job(
            set_tv_source, 'cron',
            minute=30)  # Turn the TV on/off, and set the TV source

        # Daily reset job
        # scheduler.add_job(daily_check, 'cron', hour='3', minute='0', args=[scheduler])
        # scheduler.add_job(set_daily_jobs, 'cron', hour='0', minute='1', args=[scheduler])
        scheduler.start()
        scheduler.print_jobs()

        set_hebdaily_jobs(scheduler)  # check the times for now
        logging.debug('waiting...')

        loop.run_forever()
        loop.close()
        scheduler.shutdown(wait=False)

    except Exception:
        logging.exception('unhandled exception')
    except SystemExit:
        logging.debug('System Exiting')
示例#10
0
class Scheduler:
    def __init__(self):
        # self.__jobstores = {'default': RedisJobStore(jobs_key="unicon_tasks", host='localhost', port=6379)}
        self.__executors = {'default': ThreadPoolExecutor(20)}
        self.scheduler = BackgroundScheduler(
            # jobstores=self.__jobstores,
            executors=self.__executors,
            timezone=utc)

    @staticmethod
    def handle_rule_execution(**rule):
        if rule['connector_id'] in connectors_map:
            connector = connectors_map[rule['connector_id']]()
        else:
            logger.warning("Not exist connector %s", rule['connector_id'])
            return
        tg = TaskGenerator()
        while True:
            task = tg.generate_task(rule)
            if tg.its_time_to_start():
                logger.info("[%s] start from %s to %s", task['rule_name'], task['start_time'], task['end_time'])
                connector.start(task)
                tg.new_checkpoint()
                logger.info("[%s] end work", task['rule_name'])
            else:
                break

    def add_job(self, rule):
        interval_time = timedelta(**rule["scheduler_params"]["interval"]).total_seconds()
        job = self.scheduler.add_job(self.handle_rule_execution, 'interval',
                                     kwargs=rule,
                                     seconds=interval_time,
                                     id=rule['rule_name'],
                                     name=rule['rule_name'],
                                     max_instances=1,
                                     # jitter=5,
                                     replace_existing=True,
                                     # **rule["scheduler_params"]["interval"]
                                     )
        job.modify(next_run_time=datetime.utcnow() + timedelta(seconds=random.randint(1, 15)))

    def make_tasks(self):
        logger.debug("Loading scheduler rules from %s", rule_path)
        for rule_file in os.listdir(rule_path):
            with open(f'{rule_path}/{rule_file}') as f:
                rule = yaml.load(f.read(), Loader=yaml.FullLoader)
            if rule:
                self.add_job(rule)

        self.scheduler.print_jobs()
def add_periodic_job(sched_sql_loc, function_to_run, time_df, id_modifier,
                     args):
    """
    Adds a job to the scheduler database. This function must have the same
        arguements for all runs.
    
    :param: sched_sql_loc: location of the sql job database generated by 
        this program and used by the scheduler
    :type: sched_sql_loc: string
    
    :param: function_to_run: The function that is being scheduled
    :type: csv_path_in: function   

    :param: time_df: pandas dataframe that contains when the function should
        run
    :type: time_df: pandas dataframe
    
    :param: id_modifier: string that will be added to the id for add job
    :type: string
    
    :param: args: list of arguements that are used by function_to_run
    :type: args: list   
    """
    # opne the scheduler object and associate the job database with it
    scheduler = BackgroundScheduler()
    scheduler.add_jobstore('sqlalchemy', url='sqlite:///%s' % sched_sql_loc)
    sched_time_hours = time_df['hours'].values
    sched_time_minutes = time_df['minutes'].values
    sched_time_seconds = time_df['seconds'].values
    sched_day_code = time_df['day_code'].values
    sched_index = time_df.index.values
    for ind in range(len(sched_time_hours)):
        # misfire_grace_time - seconds after the designated runtime that
        # the job is still allowed to be run
        tempargs = args.copy()
        tempargs.append(sched_index[ind])
        scheduler.add_job(function_to_run,
                          'cron',
                          day_of_week=sched_day_code[ind],
                          hour=int(sched_time_hours[ind]),
                          minute=int(sched_time_minutes[ind]),
                          second=int(sched_time_seconds[ind]),
                          misfire_grace_time=120,
                          id=(id_modifier + str(sched_index[ind])),
                          args=tempargs)
    scheduler.print_jobs()
    scheduler.start()
    scheduler.shutdown()
示例#12
0
def _initialize_scheduler():
    executors = {
        'default': ThreadPoolExecutor(20),
        'processpool': ProcessPoolExecutor(5)
    }
    job_defaults = {'coalesce': False, 'max_instances': 3}

    scheduler = BackgroundScheduler(executors=executors,
                                    job_defaults=job_defaults,
                                    timezone=utc)

    scheduler.add_job(schedulerService.run_stats, 'interval', minutes=2)

    scheduler.print_jobs()

    return scheduler
示例#13
0
class Scheduler:
    scheduler = None

    def __init__(self) -> None:
        super().__init__()
        self.scheduler = BackgroundScheduler()
        self.scheduler.start()
        self.print_schedules()

    def __del__(self):
        self.shutdown()

    def shutdown(self):
        self.scheduler.shutdown()

    def schedule_event(self, aid, dt, event, args):
        scheduled = self.scheduler.add_job(func=event,
                                           trigger='date',
                                           id=aid,
                                           run_date=dt,
                                           args=args)
        return scheduled.id

    def update_event(self, aid, dt, event, args):
        scheduled = self.scheduler.get_job(job_id=aid)
        if scheduled:
            return scheduled.id
        else:
            return self.schedule_event(aid=aid, dt=dt, event=event, args=args)

    def print_schedules(self):
        return self.scheduler.print_jobs()
示例#14
0
class DontForgetApp(rumps.App):
    """The macOS status bar application."""

    DEFAULT_TITLE = UT.ReminderRibbon

    class Menu(Enum):
        """Menu items."""

        Preferences = "Preferences..."
        ReloadConfigFile = "Reload config file"
        Quit = f"Quit {PROJECT_NAME}"

    def __init__(self):
        super(DontForgetApp, self).__init__(self.DEFAULT_TITLE,
                                            quit_button=self.Menu.Quit.value)

        logger.debug("Creating scheduler")
        self.scheduler = BackgroundScheduler()
        self.plugins: list = []

    def create_preferences_menu(self):
        """Create the preferences menu."""
        self.menu.add(
            MenuItem(self.Menu.Preferences.value,
                     callback=self.clicked_preferences))
        self.menu.add(
            MenuItem(self.Menu.ReloadConfigFile.value,
                     callback=self.clicked_reload_config_file))
        self.menu.add(rumps.separator)

    def clicked_preferences(self, _):
        """Open the config file on the preferred editor."""
        run(["open", str(CONFIG_FILE_PATH)])

    def clicked_reload_config_file(self, _):
        """Reload the config file and send it again to each loaded plugin."""
        config_yaml = load_config_file()
        for plugin in self.plugins:  # type: BasePlugin
            plugin.config_yaml = config_yaml
            plugin.reload_config()

    def start_scheduler(self) -> bool:
        """Start the scheduler."""
        logger.debug("Starting scheduler")
        self.scheduler.start()
        self.scheduler.print_jobs(out=log_file.open("a"))
        return True
示例#15
0
def main():
    try:
        scheduler = BackgroundScheduler()
        print("Starting scheduler")
        scheduler.start()

        # Connect to dynamoDB table 'schedules'
        dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
        table = dynamodb.Table('schedules')

        while True:
            # Search db for the inputted row
            response = table.scan()
            items = response['Items']
            for item in items:
                #print(item)
                device_id = int(item["deviceid"])
                setdatetime = item["setdatetime"]
                name = item["name"]
                recurrent_check = int(item["recurrent"])
                custom_freq = item["customfreq"]
                repeat_freq = item["repeatfreq"]

                # Check the recurrency of the scheduled task
                if recurrent_check == 0:  # If not recurrent, schedule job once
                    schedule_once(scheduler, device_id, name, setdatetime)

                elif recurrent_check == 1:  # If it is recurrent, check for custom or standard frequency
                    if repeat_freq == "custom":
                        # print("Custom Frequency")
                        schedule_custom(scheduler, name, setdatetime, custom_freq)
                    else:  # If repeat_freq is a standard day/week/month/year
                        #print("Standard Frequency")
                        schedule_standard(scheduler, name, setdatetime, repeat_freq)

            # Print scheduled jobs after scheduling each time from incomingtasks
            sleep(2)
            scheduler.print_jobs()
            # To keep the update real-time, constantly remove and add jobs to act as a replacing mechanism
            scheduler.remove_all_jobs()

    except:
        print(sys.exc_info()[0])
        print(sys.exc_info()[1])
示例#16
0
class Scheduler:
    def startup_scheduler(self):
        self.scheduler = BackgroundScheduler()
        logger.info("----INIT SCHEDULE OBJECT-----")
        self.scheduler.start()

        self.scheduler.add_job(auto_backup_job,
                               trigger="cron",
                               hour="3",
                               max_instances=1)
        settings = SiteSettings.get_site_settings()
        time = cron_parser(settings.webhooks.webhookTime)

        self.webhook = self.scheduler.add_job(
            post_webhooks,
            trigger="cron",
            name="webhooks",
            hour=time.hours,
            minute=time.minutes,
            max_instances=1,
        )

        logger.info(self.scheduler.print_jobs())

    def reschedule_webhooks(self):
        """
        Reads the site settings database entry to reschedule the webhooks task
        Called after each post to the webhooks endpoint.
        """
        settings = SiteSettings.get_site_settings()
        time = cron_parser(settings.webhooks.webhookTime)

        self.scheduler.reschedule_job(
            self.webhook.id,
            trigger="cron",
            hour=time.hours,
            minute=time.minutes,
        )

        logger.info(self.scheduler.print_jobs())
示例#17
0
def add_scheduler():
    jobstores = {'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')}
    executors = {
        'default': ThreadPoolExecutor(20),
        'processpool': ProcessPoolExecutor(5)
    }
    job_defaults = {'coalesce': False, 'max_instances': 3}
    scheduler = BackgroundScheduler(jobstores=jobstores,
                                    executors=executors,
                                    job_defaults=job_defaults,
                                    timezone=utc)

    scheduler.start()

    scheduler.reschedule_job(job_id='covid_job',
                             trigger='interval',
                             minutes=app.config['REQUEST_INTERVAL'])
    scheduler.reschedule_job(job_id='currencies_job',
                             trigger='interval',
                             minutes=app.config['REQUEST_INTERVAL'])

    scheduler.print_jobs()
示例#18
0
class CustomJobScheduler:
    def __init__(self):
        self.scheduler = BackgroundScheduler(executors=executors, job_defaults=job_defaults, timezone=CURRENT_TIME_ZONE)
        self.scheduler.start()

    def add_months_job(self, execute_func, month_interval, start_date):
        week_interval = month_interval * 4
        job = self.scheduler.add_job(func=execute_func, trigger='interval', weeks=week_interval,
                                     start_date=start_date)
        return job

    def add_weeks_job(self, execute_func, interval, start_date):
        job = self.scheduler.add_job(func=execute_func, trigger='interval', weeks=interval,
                                     start_date=start_date)
        return job

    def add_days_job(self, execute_func, interval, start_date):
        job = self.scheduler.add_job(func=execute_func, trigger='interval', days=interval,
                                     start_date=start_date)
        return job

    def add_hours_job(self, execute_func, interval, start_date):
        job = self.scheduler.add_job(func=execute_func, trigger='interval', hours=interval,
                                     start_date=start_date)
        return job

    def add_hours_job_now(self, execute_func, interval):
        start_time = timeUtil.add_minute(timeUtil.get_current_date_time(), 1)
        job = self.scheduler.add_job(func=execute_func, trigger='interval', hours=interval,
                                     start_date=start_time)
        return job

    def add_minutes_job(self, execute_func, interval, start_date):
        job = self.scheduler.add_job(func=execute_func, trigger='interval', minutes=interval,
                                     start_date=start_date)
        return job

    def print_jobs(self):
        self.scheduler.print_jobs()
def main():
    scheduler = BackgroundScheduler()

    #Schedule every 30 minutes
    scheduler.add_job(repeatEveryHourly, 'interval', seconds=1800)
    #scheduler.add_job(repeatEveryHourly, 'interval', seconds=5)
    #scheduler the delete every 30 days
    scheduler.add_job(deletes, 'interval', seconds=2592000)

    scheduler.start()
    scheduler.print_jobs()

    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        # This is here to simulate application activity (which keeps the main thread alive).
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Not strictly necessary if daemonic mode is enabled but should be done if possible
        scheduler.shutdown
    return
示例#20
0
def update_data(session: db.session, sched: BackgroundScheduler) -> bool:
    """
    обновляет данные всех трех таблиц, скачивая архив из ресурса

    Returns:
    """
    global count
    sched.print_jobs()
    print('Count: ', count)
    count += 1
    start_time = time.time()
    try:
        download()
    except Exception as e:
        print(e)
    try:
        update_currency(session)
        update_saler(session)
        make_new_pair(session)
    except Exception as e:
        print(e)
    print('Count: ', count)
    print(f'! {time.time() - start_time}')
示例#21
0
def test3():
    """定时执行任务,暂停,恢复"""
    start_time = time.time()
    scheduler = BackgroundScheduler()
    scheduler.add_job(my_job, 'interval', args=('123',),seconds=1, id='my_job_id') # 每隔1秒执行一次my_job函数,args为函数my_job的输入参数;id:可省略;
    scheduler.start() # 程序运行到这里,任务没有运行完也会往后执行,既执行后面的任务,又执行这个任务。
    print('运行到了这里1')
    while (scheduler.state):
        if time.time() - start_time >5:
            print('暂停作业')
            scheduler.pause() # 暂停作业:
            break
    print('恢复作业')
    if time.time() - start_time >5:
        scheduler.resume() # 
    time.sleep(4)
    print('当前任务列表:{}'.format(scheduler.get_jobs())) # 获得调度作业的列表,可以使用 get_jobs() 来完成,它会返回所有的job实例
    scheduler.get_job('my_job_id') # 获取id为my_job_id的作业实例
    
    scheduler.print_jobs() # 输出所有格式化的作业列表。
    
    print('移除作业')
    # scheduler.remove_job('my_job_id') # 移除id为my_job_id的作业
    scheduler.remove_all_jobs() # 移除所有的作业
示例#22
0
def test4():
    """定时执行任务,关闭调度器"""
    start_time = time.time()
    scheduler = BackgroundScheduler()
    scheduler.add_job(my_job, 'interval', args=('123',),seconds=1, id='my_job_id') 
    # 每隔1秒执行一次my_job函数,args为函数my_job的输入参数;id:可省略;
    
    scheduler.start() # 程序运行到这里,任务没有运行完也会往后执行,既执行后面的任务,又执行这个任务。
    print('运行到了这里1')
    
    #默认情况下调度器会等待所有正在运行的作业完成后,关闭所有的调度器和作业存储。如果你不想等待,可以将wait选项设置为False。
    time.sleep(1)
    print('关闭所有的调度器和作业存储')
    #scheduler.shutdown()
    scheduler.shutdown(wait=False)
    print("输出所有格式化的作业列表:{}".format(scheduler.print_jobs())) # 输出所有格式化的作业列表。
示例#23
0
def test4():
    """定时执行任务,关闭调度器"""
    start_time = time.time()
    scheduler = BackgroundScheduler()
    scheduler.add_job(my_job,
                      'interval',
                      args=('123', ),
                      seconds=1,
                      id='my_job_id')
    # 每隔1秒执行一次my_job函数,args为函数my_job的输入参数;id:可省略;

    scheduler.start()  # 程序运行到这里,任务没有运行完也会往后执行,既执行后面的任务,又执行这个任务。
    print('运行到了这里1')

    #默认情况下调度器会等待所有正在运行的作业完成后,关闭所有的调度器和作业存储。如果你不想等待,可以将wait选项设置为False。
    time.sleep(1)
    print('关闭所有的调度器和作业存储')
    #scheduler.shutdown()
    scheduler.shutdown(wait=False)
    print("输出所有格式化的作业列表:{}".format(scheduler.print_jobs()))  # 输出所有格式化的作业列表。
示例#24
0
class config:
	__white = (255, 255, 255)
	__red = (255, 0, 0)
	__color = ( 0, 255, 255 )
	__colorInv = __red
	__colorFile = "data/configFiles/colorFile.txt"
	__brightnessFile = "data/configFiles/brightnessFile.txt"
	__fontFile = "data/configFiles/fontFile.txt"
	__speedFile = "data/configFiles/speedFile.txt"
	__viewFile = "data/configFiles/viewFile.txt"
	__sleepFile = "data/configFiles/sleepTimer.txt"

	__fileIO = fileIO( )

	def __init__( self ):
		#self.__vcgencmd = Vcgencmd( )
		self.__valChange = ["", "", ""]
		self.__fonts = [0] *8
		self.__cSize = 0

		self.__scheduler = BackgroundScheduler( )
		self.__scheduler.start( )

		self.__sleepF1 = True
		self.__sleepF2 = True

	def setColor( self ):
		color, colorInv = self.__fileIO.simpleRead( self.__colorFile, separator=":" )
		self.__color = [int( color[ i : i +2 ], 16 ) for i in range( 1, len(color) -1, 2 )]
		self.__colorInv = [int( colorInv[ i : i +2 ], 16 ) for i in range( 1, len(colorInv) -1, 2 )]
		if( self.__color == self.__white ): 
			self.__colorInv = self.__red

		return self.__color, self.__colorInv

	def setBrightness( self ):
		brightness = self.__fileIO.simpleRead( self.__brightnessFile )
		if( sys.platform == "linux" or sys.platform == "linux2" ):
			import os
			os.system( 'xbacklight -set ' + brightness )
		elif( sys.platform == "win32" ):
			import wmi
			wmi.WMI( namespace='wmi' ).WmiMonitorBrightnessMethods( )[0].WmiSetBrightness( int( brightness ), 1 )

	def setSleepTime( self ):
		sleep = self.__fileIO.simpleRead( self.__sleepFile, multiLine=True )
		if( len( sleep ) > 4 ):
			if( self.__valChange[0] != sleep[0] or self.__valChange[1] != sleep[1] ):
				try:
					self.__sleepF1 = True
					self.__scheduler.remove_job( 'dpoff' )
					self.__scheduler.remove_job( 'dpon' )
				except:
					print( "IN config::setSleepTime: jobs dont exist!" )
			if( self.__valChange[2] != sleep[2] ):
				try:
					self.__sleepF2 = True
					self.__scheduler.remove_job( "dim" )
				except:
					print( "IN config::setSleepTime: jobs dont exist!" )

			if( sleep[3] in "False" and self.__sleepF1 ):
				self.__sleepF1 = False
				hr = int( sleep[0].split(":")[0] )
				mi = int( sleep[0].split(":")[1] )
				self.__scheduler.add_job( lambda: self.__vcgencmd.display_power_off( 2 ), "cron", hour=hr, minute=mi, id='dpoff' )
				#self.__scheduler.add_job( lambda: self.displayOffTest(hr), "cron", hour=hr, minute=mi, id='dpoff' )
				hr = int( sleep[1].split(":")[0] )
				mi = int( sleep[1].split(":")[1] )
				self.__scheduler.add_job( lambda: self.__vcgencmd.display_power_on( 2 ), "cron", hour=hr, minute=mi, id='dpon')
				#self.__scheduler.add_job( lambda: self.displayOnTest(hr), "cron", hour=hr, minute=mi, id='dpon' )
			elif( sleep[3] in "True" and not self.__sleepF1 ):
				self.__sleepF1 = True
				self.__scheduler.remove_job( 'dpoff' )
				self.__scheduler.remove_job( 'dpon' )
				self.__vcgencmd.display_power_on( 2 )
				#print( "Display on: " )
			if( sleep[4] in "False" and self.__sleepF2 ):
				self.__sleepF2 = False
				self.__scheduler.add_job( lambda: self.__vcgencmd.display_power_off( 2 ), "interval", minutes=int( sleep[2] ), id='dim' )
				#self.__scheduler.add_job( lambda: self.displayOffTest(int(sleep[2])), "interval", minutes=int( sleep[2] ), id='dim' )
			elif( sleep[4] in "True" and not self.__sleepF2 ):
				self.__sleepF2 = True
				self.__scheduler.remove_job( 'dim' )
				self.__vcgencmd.display_power_on( 2 )
				#print( "Display on: " )
			self.__valChange = [sleep[0], sleep[1], sleep[2]]
			print( self.__scheduler.print_jobs( ))

	def displayOffTest( self, hr ):
		print( "Display off: ", hr )
	def displayOnTest( self, hr ):
		print( "Display on: ", hr )

	def readFontFromFile( self ):
		font = self.__fileIO.simpleRead( self.__fontFile, multiLine=True )
		font[ 0 ] = font[ 0 ].split( "," )[ 0 ]
		font[ 1 ] = int( font[ 1 ])
		if( len( font ) == 2 ):
			font.append( False )
			font.append( False )
		elif( len( font ) == 3 ):
			if( 'Bold' in font[ 2 ]):
				font[ 2 ] = True
				font.append( False )
			else:
				font[ 2 ] = False
				font.append( True )
		elif( len( font ) == 4 ):
			font[ 2 ] = True
			font[ 3 ] = True
		return font

	def getFont( self, index ):
		return self.__fonts[index]
	def setCSize( self, size ):
		self.__cSize = size

	def getSpeed( self ):
		speed = self.__fileIO.simpleRead( self.__speedFile )
		if( "Non" in speed ):
			return 0
		else:
			return int( speed ) *1000

	def getView( self ):
		return self.__fileIO.simpleRead( self.__viewFile, multiLine=True )[0]

	def getAllFonts( self ):
		fontName, fontSize, bold, italic = self.readFontFromFile( )
		try:
			self.__fonts[0] = pygame.font.SysFont( fontName, fontSize + self.__cSize, bold=bold, italic=italic )#calendar
			self.__fonts[1] = pygame.font.SysFont( fontName, fontSize + 0 , bold=bold, italic=italic )#date
			self.__fonts[2] = pygame.font.SysFont( fontName, fontSize + 32 , bold=bold, italic=italic )#time
			self.__fonts[3] = pygame.font.SysFont( fontName, fontSize -12 , bold=bold, italic=italic )#events
			self.__fonts[4] = pygame.font.SysFont( fontName, fontSize - 12 , bold=bold, italic=italic )#news
			self.__fonts[5] = pygame.font.SysFont( fontName, fontSize - 4, bold=bold, italic=italic )#weather
			self.__fonts[6] = pygame.font.SysFont( fontName, fontSize - 12 , bold=bold, italic=italic )#hour
			self.__fonts[7] = pygame.font.SysFont( fontName, fontSize - 18 , bold=bold, italic=italic )#hour
		except:
			self.__fonts[0] = pygame.font.Font( fontName, fontSize , bold=bold, italic=italic )
			self.__fonts[1] = pygame.font.Font( fontName, fontSize + 0 , bold=bold, italic=italic )
			self.__fonts[2] = pygame.font.Font( fontName, fontSize + 32 , bold=bold, italic=italic )
			self.__fonts[3] = pygame.font.Font( fontName, fontSize -12 , bold=bold, italic=italic )
			self.__fonts[4] = pygame.font.Font( fontName, fontSize - 12 , bold=bold, italic=italic )
			self.__fonts[5] = pygame.font.Font( fontName, fontSize - 4 , bold=bold, italic=italic )
			self.__fonts[6] = pygame.font.Font( fontName, fontSize - 12 , bold=bold, italic=italic )
			self.__fonts[7] = pygame.font.Font( fontName, fontSize - 18 , bold=bold, italic=italic )
		return self.__fonts
示例#25
0
nom_scheduler.add_job(christmas_lights_off,
                      'cron',
                      month='1,2,3,10,11,12',
                      hour=lights_win_stop_h,
                      minute=lights_win_stop_m)

#Hourly Lights
for hour in range(0, 6):
    nom_scheduler.add_job(lights_on, 'cron', hour=hour, minute=0)
    nom_scheduler.add_job(lights_off,
                          'cron',
                          hour=hour,
                          minute=lights_hourly_dur_m)

nom_scheduler.print_jobs()

nom_scheduler.start()

current_time = datetime.now().strftime('%H:%M:%S')
print(current_time)

#------------ Remote Commands ------------

setup_gpio()

ev_scheduler = BackgroundScheduler()
ev_scheduler.start()

session = fbchat.Session.login(email, password)
listener = fbchat.Listener(session=session, chat_on=False, foreground=False)
class SpecificTimeReporter(object):
    """
    This class is used to get the real-time market data at specific time everyday from yahoo finance database,
    the accessed data will not be saved at local,
    please use this with my Stock Data Reader class
    """
    def __init__(self, function):
        """
        :param function: function of the arranged job, in this case,
        it should be the getCurrentMarketData function
        """
        self._scheduler = None
        self.function = function
        self.count = 1
        self._all_job = {}
        self.start()

    def start(self):
        """
        start the reporter
        :return: None
        """
        self._scheduler = BackgroundScheduler()
        self._scheduler.start()

    def convertInt2Time(self, hour, minute, second):
        """
        You do not need to call this method, you can treat this as a private method
        :param hour: integer ranging from 0 to 23
        :param minute: integer ranging from 0 to 59
        :param second: integer ranging from 0 to 59
        :return: string format of time
        """
        ans = ""
        if hour < 10:
            ans = ans + "0" + str(hour)
        else:
            ans = ans + str(hour)
        if minute < 10:
            ans = ans + "0" + str(minute)
        else:
            ans = ans + str(minute)
        if second < 10:
            ans = ans + "0" + str(second)
        else:
            ans = ans + str(second)
        return ans

    def addJob(self, hour, minute, second, *args):
        """
        add a reporter
        :param hour: integer ranging from 0 to 23
        :param minute: integer ranging from 0 to 59
        :param second: integer ranging from 0 to 59
        :param args: tickerList,like:["AAPL","IBM","JPM"]
        :return: None
        """
        timeString = self.convertInt2Time(hour, minute, second)

        if timeString not in self._all_job:
            self._all_job[timeString] = str(self.count)
            self._scheduler.add_job(self.function,
                                    trigger='cron',
                                    hour=hour,
                                    minute=minute,
                                    second=second,
                                    args=args,
                                    id=str(self.count))
            self.count = self.count + 1
        else:
            self._scheduler.reschedule_job(self._all_job[timeString],
                                           trigger='cron',
                                           hour=hour,
                                           minute=minute,
                                           second=second)

    def removeJob(self, hour, minute, second):
        """
        remove a reporter
        :param hour: integer ranging from 0 to 23
        :param minute: integer ranging from 0 to 59
        :param second: integer ranging from 0 to 59
        :return: None
        """
        timeString = self.convertInt2Time(hour, minute, second)
        if timeString not in self._all_job:
            warnings.warn("Job not found!")
        else:
            self._scheduler.remove_job(self._all_job[timeString])

    def removeAllJobs(self):
        """
        remove all reporters
        :return: None
        """
        self._scheduler.remove_all_jobs()

    def pause(self):
        """
        pause all reporters
        :return: None
        """
        self._scheduler.pause()

    def resume(self):
        """
        resume the paused reporters
        :return: None
        """
        self._scheduler.resume()

    def getAllJobs(self):
        """
        print the information of all reporters
        :return: None
        """
        self._scheduler.print_jobs()

    def shutDown(self):
        """
        shut down all reporters
        :return: None
        """
        self._scheduler.shutdown()
class PeriodicReporter(object):
    """
    This class is used to periodically get real-time market data from Yahoo finance database,
    the accessed data will not be saved at local,
    please use this with my Stock Data Reader class
    """
    def __init__(self, function):
        """

        :param function: function of the arranged job, in this case,
        it should be the getCurrentMarketData function
        """
        self._scheduler = None
        self.function = function
        self.existingJob = False
        self.start()

    def start(self):
        """
        method to start the reporter
        :return: None
        """
        self._scheduler = BackgroundScheduler()
        self._scheduler.start()

    def addJob(self, interval, *args):
        """
        add a reporter
        :param interval: the interval between two reports, 20 means 20 seconds, etc...
        :param args: tickerList,like:["AAPL","IBM","JPM"]
        :return: None
        """
        if not self.existingJob:
            self._scheduler.add_job(self.function,
                                    trigger='interval',
                                    seconds=interval,
                                    args=args)
            self.existingJob = True
        else:
            warnings.warn("Existing job will be removed!")
            self._scheduler.remove_all_jobs()
            self._scheduler.add_job(self.function,
                                    trigger='interval',
                                    seconds=interval,
                                    args=args)

    def removeJob(self):
        """
        remove the current reporter
        :return: None
        """
        self._scheduler.remove_all_jobs()
        self.existingJob = False

    def pause(self):
        """
        pause the current reporter
        :return: None
        """
        self._scheduler.pause()

    def resume(self):
        """
        resume the paused reporter
        :return: None
        """
        self._scheduler.resume()

    def getJob(self):
        """
        print the details of the current reporter
        :return: None
        """
        self._scheduler.print_jobs()

    def shutDown(self):
        """
        shut down the reporter
        :return: None
        """
        self._scheduler.shutdown()
示例#28
0
def add_schedule_backup_job():
    # if __name__ == '__main__':
    os_user = config.OS_USER

    os_password = config.OS_APPS_PASSWD

    scheduler = BackgroundScheduler()  # 默认内存的jobstore

    url = "sqlite:////home/apps/dbajob.sqlite"

    scheduler.add_jobstore("sqlalchemy", url=url, alias="sqlite_js")

    scheduler.print_jobs()

    print "a"

    scheduler.remove_all_jobs(jobstore="sqlite_js")

    scheduler.print_jobs()

    print "remove"

    # v_current_jobs = scheduler.get_jobs()

    # print v_current_jobs

    # if v_current_jobs:  # 如果job存在的话,先请客

    #     scheduler.remove_job('backup')

    # 连接配置中心库,获取数据库备份周期等信息
    db = Connection("/tmp/mysql3306.sock", config.DB_NAME, config.DB_USER, config.DB_PASSWD, time_zone="+8:00")

    v_sql = r"""SELECT a.instance_id,b.ip,b.port,a.backup_interval_type,a.backup_start_time from mysql_ins_bak_setup a,tag b where 
        a.instance_id=b.id """

    print v_sql

    bak_server_list = db.query(v_sql)

    if bak_server_list:  # 有server需要配置

        i = 0

        # 把还没有开始的调度任务,置为手工结束 backup_result_type=4
        v_manual_end_sql = "update mysql_ins_bak_log set backup_result_type=4 where backup_result_type=0"

        db.execute(v_manual_end_sql)

        for bak_server in bak_server_list:

            instance_id = bak_server["instance_id"]

            from_host = bak_server["ip"]

            # print from_host

            mysql_port = bak_server["port"]

            backup_interval_type = bak_server["backup_interval_type"]

            backup_start_time = bak_server["backup_start_time"]

            str_start_date = time.strftime("%Y-%m-%d") + " " + backup_start_time

            print str_start_date

            v_job_id = "backup_%s_%s" % (from_host, str(mysql_port))

            if backup_interval_type == 1:  # every day

                # scheduler.add_interval_job(backup, days=1, start_date=str_start_date, args=[from_host, mysql_port, os_user, os_password], jobstore='file')

                scheduler.add_job(
                    backup,
                    "interval",
                    id=v_job_id,
                    days=1,
                    start_date=str_start_date,
                    args=[from_host, mysql_port, os_user, os_password],
                    replace_existing=True,
                    jobstore="sqlite_js",
                )

            elif backup_interval_type == 2:  # every week weeks=1

                scheduler.add_job(
                    backup,
                    "interval",
                    id=v_job_id,
                    weeks=1,
                    start_date=str_start_date,
                    args=[from_host, mysql_port, os_user, os_password],
                    replace_existing=True,
                    jobstore="sqlite_js",
                )

            elif backup_interval_type == 3:  # every hour hours=1

                scheduler.add_job(
                    backup,
                    "interval",
                    id=v_job_id,
                    hours=1,
                    start_date=str_start_date,
                    args=[from_host, mysql_port, os_user, os_password],
                    replace_existing=True,
                    jobstore="sqlite_js",
                )

            else:
                pass
            # 开始在数据库记录备份的调度任务状态 0:调度任务已启动,实际备份还没有开始

            v_sche_start_sql = """insert into mysql_ins_bak_log(instance_id,backup_result_type) 
            values(%d,0)""" % (
                instance_id
            )

            db.execute(v_sche_start_sql)

            i = i + 1

        scheduler.print_jobs()

        print "b"

        scheduler.start()

        scheduler.print_jobs()

        print "c"

    db.close()
示例#29
0
# -*- coding:utf-8 -*-

"""
Created on 2015年12月5日

@author: LeoBrilliant
"""

from apscheduler.schedulers.background import BackgroundScheduler
from time import sleep

i = 0


def RoundWork():
    i += 1
    print("i = %d" % i)


sched = BackgroundScheduler()

job = sched.add_job(RoundWork, "interval", seconds=2, id="my_job_id")

sched.print_jobs()

sched.start()

sleep(10)

sched.shutdown()
示例#30
0
class MainRunner(object):

    class FilterAllLog(logging.Filter):
        # default we will filter logger from apscheduler.executors.default, apscheduler.scheduler,
        # you can config filter logger in config.json
        def filter(self, record):
            return ""

    def __init__(self, input_cmd_config_fp, input_job_config_fp, input_config_fp):

        # init value
        cmd_config_fp = os.path.abspath(input_cmd_config_fp)
        job_config_fp = os.path.abspath(input_job_config_fp)
        config_fp = os.path.abspath(input_config_fp)

        # load configuration json files
        self.cmd_config = CommonUtil.load_json_file(cmd_config_fp)
        self.job_config = CommonUtil.load_json_file(job_config_fp)
        self.config = CommonUtil.load_json_file(config_fp)

        # init schedulers
        self.scheduler = BackgroundScheduler()
        self.scheduler.add_jobstore('sqlalchemy', url=self.config['job_store_url'])
        self.scheduler.start()

        # init variables
        mananger = Manager()
        self.sync_queue = mananger.Queue()
        self.async_queue = mananger.Queue()
        self.current_job_list = []

        # Slack Sending Queue
        # TODO: prevent the Slack bot is disable, the sending queue will use too much memory.
        self.slack_sending_queue = mananger.Queue(50)

        # init logger
        self.set_logging(self.config['log_level'], self.config['log_filter'])

    def set_logging(self, log_level, log_filter_list):
        default_log_format = '%(asctime)s %(levelname)s [%(name)s.%(funcName)s] %(message)s'
        default_datefmt = '%Y-%m-%d %H:%M'
        if log_level.lower() == "debug":
            logging.basicConfig(level=logging.DEBUG, format=default_log_format, datefmt=default_datefmt)
        else:
            logging.basicConfig(level=logging.INFO, format=default_log_format, datefmt=default_datefmt)

        my_filter = self.FilterAllLog()
        for target_logger in log_filter_list:
            logging.getLogger(target_logger).addFilter(my_filter)

    def scheduler_del_job(self, **kwargs):
        input_cmd_str = kwargs.get("input_cmd_str", "")
        cmd_str_list = input_cmd_str.split(" ")
        if len(cmd_str_list) == 2:
            job_id = cmd_str_list[1]
            current_job_list = self.scheduler.get_jobs()
            current_job_id_list = [j.id for j in current_job_list]
            if job_id in current_job_id_list:
                self.scheduler.remove_job(job_id)
            else:
                logging.error("Cannot find the specify job id [%s]" % job_id)
        else:
            logging.error("Incorrect cmd format! [%s]" % input_cmd_str)

    def scheduler_list_job(self, **kwargs):
        self.scheduler.print_jobs()

    def scheduler_shutdown(self, **kwargs):
        self.scheduler.shutdown()
        sys.exit(0)

    def list_all_commands(self, **kwargs):
        print "Current supported commands as below:"
        print "-" * 80
        for cmd_str in self.cmd_config['cmd-settings']:
            print '{:30s} {:50s} '.format(cmd_str, self.cmd_config['cmd-settings'][cmd_str]['desc'])
        print "-" * 80

    def scheduler_job_handler(self, input_cmd_obj, input_cmd_str):
        cmd_match_pattern = input_cmd_obj.keys()[0]
        func_point = getattr(self, input_cmd_obj[cmd_match_pattern]['func-name'])
        func_point(cmd_configs=input_cmd_obj[cmd_match_pattern]['configs'], input_cmd_str=input_cmd_str)

    def cmd_queue_composer(self, input_cmd_str):
        for cmd_pattern in self.cmd_config['cmd-settings']:
            re_compile_obj = re.compile(cmd_pattern)
            re_match_obj = re_compile_obj.search(input_cmd_str)
            if re_match_obj:
                current_command_obj = self.cmd_config['cmd-settings'][cmd_pattern]
                logging.debug("job matched [%s]" % cmd_pattern)
                target_queue_type = current_command_obj.get('queue-type', None)
                if target_queue_type == "async":
                    self.async_queue.put({"cmd_obj": current_command_obj, "cmd_pattern": cmd_pattern, "input_cmd_str": input_cmd_str})
                elif target_queue_type == "sync":
                    self.sync_queue.put({"cmd_obj": current_command_obj, "cmd_pattern": cmd_pattern, "input_cmd_str": input_cmd_str})
                else:
                    self.scheduler_job_handler({cmd_pattern: current_command_obj}, input_cmd_str)
                break

    def load_default_jobs(self, input_scheduler, input_job_config):
        current_jobs = input_scheduler.get_jobs()
        current_jobs_name = [job.name for job in current_jobs]
        for job_name in input_job_config:
            if input_job_config[job_name]['default-loaded']:
                if job_name not in current_jobs_name:
                    func_point = getattr(importlib.import_module(input_job_config[job_name]['module-path']), job_name)
                    self.scheduler.add_job(func_point, input_job_config[job_name]['trigger-type'],
                                           id=job_name,
                                           seconds=input_job_config[job_name]['interval'],
                                           max_instances=input_job_config[job_name]['max-instances'],
                                           kwargs={
                                               'async_queue': self.async_queue,
                                               'sync_queue': self.sync_queue,
                                               'slack_sending_queue': self.slack_sending_queue,
                                               'configs': input_job_config[job_name]['configs'],
                                               'cmd_config': self.cmd_config}
                                           )

    def job_exception_listener(self, event):
        if event.exception:
            logging.error("Job [%s] crashed [%s]" % (event.job_id, event.exception))
            logging.error(event.traceback)

    def add_event_listener(self):
        self.scheduler.add_listener(self.job_exception_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

    def run(self):
        # load default job into scheduler if the job is not exist
        self.load_default_jobs(self.scheduler, self.job_config)

        # add event listener into scheduler
        self.add_event_listener()

        # enter the loop to receive the interactive command
        while True:
            user_input = raw_input()
            self.cmd_queue_composer(user_input)
            time.sleep(3)
    return True


# Enable debug for apscheduler
logging.basicConfig()
logging.getLogger('apscheduler').setLevel(logging.DEBUG)

# Job setting
job_defaults = {
    'coalesce': False,
    # Execution of job skipped: maximum number of running instances reached (8)
    'max_instances': 8
}

scheduler = BackgroundScheduler(job_defaults=job_defaults)

job = scheduler.add_job(func_as_task_to_do, 'interval', seconds=1)
scheduler.print_jobs()
scheduler.start()

# Because of the scheduler is background scheduler not blocking scheduler, so we use a endless loop
print('Press Ctrl + {key} to exit.'.format(key='Break' if os.name == 'nt' else 'C'))
try:
    while True:
        time.sleep(2)
except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
    print('Exit now!')
示例#32
0
class SkyzeSchedulerService(SkyzeServiceAbstract):
    """Skyze inter-service message logger"""
    def __init__(self, message_bus):
        """Constructor
       Scheduler doco: http://apscheduler.readthedocs.io/en/latest/userguide.html"""
        #self.__message_bus = None
        path_to_service = "Skyze_Scheduler_Service"
        super().__init__(message_bus=message_bus, log_path=path_to_service)

        # Create Scheduler
        # BlockingScheduler: use when the scheduler is the only thing
        #                    running in your process
        # BackgroundScheduler: use when you’re not using any of the
        #             frameworks below, and want the scheduler to run
        #             in the background inside your application
        self._sched = BackgroundScheduler()

    def test(self):
        start_time = datetime.now()
        print('=== Skyze Scheduler TEST RUN ========== ' + str(start_time) +
              ' ========== ')
        print()

        market_list = [
            'ETH_BTC', 'LTC_BTC', 'HSR_BTC', 'PAC_DOGE', 'SPR_BTC', 'ODN_BTC'
        ]
        message_list = [
            MessageMarketDataUpdaterRun("Cryptopia", market_list, "Tick"),
            MessageMarketDataUpdaterRunAll("Poloniex"),
            MessageScreenerRun("Mike's Screener")
        ]

        for i in range(1, 10):
            msg_number = randint(0, 2)
            msg = message_list[msg_number]
            self._sendMessage(msg)
        print(f"Test Messages published")

    def send_random_message(self):
        market_list = [
            'ETH_BTC', 'LTC_BTC', 'HSR_BTC', 'PAC_DOGE', 'SPR_BTC', 'ODN_BTC'
        ]

        message_list = [
            MessageMarketDataUpdaterRun("Cryptopia", market_list, "Tick"),
            MessageMarketDataUpdaterRunAll("Poloniex"),
            MessageScreenerRun("Mike's Screener")
        ]

        msg_number = randint(0, 2)
        msg = message_list[msg_number]
        log_msg = f"Scheduler Service::send_random_message - {datetime.now()} - {msg.getJSON()}"
        self._logger.log_info(log_msg)
        self._sendMessage(msg)

    # ========================================================================
    # ----- Jobs to Schedule =================================================
    # ========================================================================
    def bitfinex_90min_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering:: Bitfinex 90 minute Update'
        self._logger.log_info(log_msg)
        message = MessageMarketDataUpdaterRun("Bitfinex",
                                              "All",
                                              market_pairs=None)
        self._sendMessage(message)

    def bittrex_12hr_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering:: Bittrex 12 hourly Update'
        self._logger.log_info(log_msg)
        message = MessageMarketDataUpdaterRun("Bittrex",
                                              "All",
                                              market_pairs=None)
        self._sendMessage(message)

    def kraken_5hr_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering:: Kraken 12 hourly Update'
        self._logger.log_info(log_msg)
        message = MessageMarketDataUpdaterRun("Kraken",
                                              "All",
                                              market_pairs=None)
        self._sendMessage(message)

    #@sched.scheduled_job('cron', day_of_week='mon-sun', hour='0-23', minute=1)
    def cryptopia_hourly_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering:: Cryptopia Hourly Update'
        self._logger.log_info(log_msg)
        hourly_pairs = [
            'ETH_BTC', 'LTC_BTC', 'HSR_BTC', 'PAC_DOGE', 'SPR_BTC', 'ODN_BTC'
        ]
        message = MessageMarketDataUpdaterRun("Cryptopia",
                                              "Tick",
                                              market_pairs=hourly_pairs)
        self._sendMessage(message)

    def cryptopia_daily_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering:: Cryptopia Hourly Update'
        self._logger.log_info(log_msg)
        message = MessageMarketDataUpdaterRun("Cryptopia",
                                              "Tick",
                                              market_pairs=None)
        self._sendMessage(message)

    #@sched.scheduled_job('cron', day_of_week='mon-sun', hour=14, minute=30)
    def cmc_daily_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering: : CMC all markets Daily Update at 2: 30pm.'
        self._logger.log_info(log_msg)
        message = MessageMarketDataUpdaterRun("CoinMarketCap",
                                              "Daily",
                                              market_pairs=None)
        self._sendMessage(message)

    #@sched.scheduled_job('cron', day_of_week='mon-sun', hour=10, minute=12)
    def poloniex_daily_update(self, market_pairs=None):
        log_msg = 'Scheduler:: Triggering:: Poloniex all markets Daily Update at 10:12am'
        self._logger.log_info(log_msg)
        message = MessageMarketDataUpdaterRun("Poloniex",
                                              "All",
                                              market_pairs=None)
        self._sendMessage(message)

    # ========================================================================
    # ====== Start the Scheduler =============================================
    # ========================================================================
    def start(self):
        """Schedules the jobs and starts the scheduler"""
        start_time = datetime.now()
        print('=== Skyze Scheduler ========== ' + str(start_time) +
              ' ==========\n')

        # === Create the scheduled jobs
        # TODO Get list of jobs from settings file
        #job = sched.add_job(self.send_random_message, 'interval', minutes=1)

        # Bitfinex 90 minute-ly for all markets
        job = self._sched.add_job(self.bitfinex_90min_update,
                                  'interval',
                                  minutes=90)

        # Bittrex 12 Hour-ly for all markets
        job = self._sched.add_job(self.bittrex_12hr_update,
                                  'interval',
                                  hours=12)

        # Kraken 90 minute-ly for all markets
        job = self._sched.add_job(self.kraken_5hr_update, 'interval', hours=5)

        # Cryptopia Daily - hourly for high volume markets
        job = self._sched.add_job(self.cryptopia_hourly_update,
                                  'cron',
                                  day_of_week='mon-sun',
                                  hour='0-23')
        #                          'interval', hours=1)

        # Poloniex only needs daily update - as can request that much history
        job = self._sched.add_job(self.poloniex_daily_update,
                                  'cron',
                                  day_of_week='mon-sun',
                                  hour=20,
                                  minute=12)  # 20:12

        # Cryptopia Daily run 1 - twice a day for low volume markets
        job = self._sched.add_job(self.cryptopia_daily_update,
                                  'cron',
                                  day_of_week='mon-sun',
                                  hour=21,
                                  minute=35)  # 21:35

        # CoinMarketCap Daily update - as can request that much history
        job = self._sched.add_job(self.cmc_daily_update,
                                  'cron',
                                  day_of_week='mon-sun',
                                  hour=1,
                                  minute=8)  # 01:08

        # Cryptopia Daily run 2 - twice a day for low volume markets
        job = self._sched.add_job(self.cryptopia_daily_update,
                                  'cron',
                                  day_of_week='mon-sun',
                                  hour=8,
                                  minute=8)  # 08:08

        # === Print the list of jobs and start the scheduler
        self._sched.print_jobs()
        self._sched.start()

    def receiveMessage(self, message_received):
        """Gets the messages from the bus, unpacks any data and routes internally"""
        # Parent class processing
        super().receiveMessage(message_received)
        # Route to appropriate service
        message_type = message_received.getMessageType()
        if message_type == SkyzeMessageType.SCHEDULER_RUN:
            self.start()
        elif message_type == SkyzeMessageType.SCHEDULER_TEST:
            self.test()
        else:
            self._unknownMessageTypeError(message_received)
示例#33
0
def start():
    scheduler = BackgroundScheduler()
    scheduler.add_job(task.change_data, 'interval', minutes=10)
    print("Starting....")
    scheduler.start()
    print(scheduler.print_jobs())
示例#34
0
class Snips(object):
    def __init__(self):
        self.fichero = __import__('action-Actions')
        self.usuario = ""
        self.idFichero = 0
        self.nombreCampos = [
            'Fecha Creación', 'Id', 'Tipo', '¿Repetitivo?', 'Frecuencia',
            'Fecha', 'Medicamento', 'Nombre_Usuario', 'Modo de aceptar',
            'Salida_error'
        ]
        if (not os.path.exists('/home/pi/Reporte.csv')):
            with open('/home/pi/Reporte.csv', 'a+') as csvfile:
                escritor = csv.DictWriter(csvfile,
                                          fieldnames=self.nombreCampos)
                escritor.writeheader()
        self.planificador = BackgroundScheduler(
            {'apscheduler.timezone': 'Europe/Madrid'})
        self.planificador1 = BackgroundScheduler(
            {'apscheduler.timezone': 'Europe/Madrid'})
        self.BaseDeDatos = BaseDeDatos()
        self.planificador.start()
        self.planificador1.start()
        self.BaseDeDatos.conectarDB()
        self.BaseDeDatos.crearTabla()
        self.BaseDeDatos.insertarUsuario('default')
        self.usuario = self.BaseDeDatos.usuarioActivo()
        if (not self.usuario):
            self.BaseDeDatos.cambiarUsuarioActivo('default')
            self.usuario = 'default'
        self.crearRecordatorios(self.fichero)
        ActHilos = self.sincronizarEventos(self)
        ActHilos.start()

    def existe_Trabajo(self, trabajo):
        enc = False
        if (self.planificador.get_jobs()):
            for x in self.planificador.get_jobs():
                if (x.id.__eq__(trabajo)):
                    return True
        return enc

    def existe_Trabajo1(self, trabajo):
        enc = False
        if (self.planificador1.get_jobs()):
            for x in self.planificador1.get_jobs():
                if (x.id.__eq__(trabajo)):
                    return True
        return enc

    def dia_sem(self, i):
        switcher = {
            'Lunes': 0,
            'Martes': 1,
            'Miercoles': 2,
            'Jueves': 3,
            'Viernes': 4,
            'Sabado': 5,
            'Domingo': 6
        }
        return switcher.get(i, str(i))

    def t(self):
        self.idFichero += 1

    def log(self, e, usuario, Modo, Tipo, mensage):
        with open('/home/pi/Reporte.csv', 'a+') as csvfile:
            escritor = csv.DictWriter(csvfile, fieldnames=self.nombreCampos)
            fecha = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            if (e):
                if (e.rep):
                    escritor.writerow({
                        'Fecha Creación': fecha,
                        'Id': str(self.idFichero),
                        'Tipo': Tipo,
                        '¿Repetitivo?': 'Si',
                        'Fecha': str(e.fecha),
                        'Frecuencia': e.cuando,
                        'Medicamento': e.med,
                        'Nombre_Usuario': e.usuario,
                        'Modo de aceptar': '',
                        'Salida_error': ''
                    })
                else:
                    escritor.writerow({
                        'Fecha Creación': fecha,
                        'Id': str(self.idFichero),
                        'Tipo': Tipo,
                        '¿Repetitivo?': 'No',
                        'Fecha': str(e.fecha),
                        'Frecuencia': '',
                        'Medicamento': e.med,
                        'Nombre_Usuario': e.usuario,
                        'Modo de aceptar': '',
                        'Salida_error': ''
                    })
            else:
                escritor.writerow({
                    'Fecha Creación': fecha,
                    'Id': str(self.idFichero),
                    'Tipo': Tipo,
                    '¿Repetitivo?': '',
                    'Fecha': '',
                    'Frecuencia': '',
                    'Medicamento': '',
                    'Nombre_Usuario': usuario,
                    'Modo de aceptar': Modo,
                    'Salida_error': mensage
                })
        self.t()

    def anadirEvento(self, evento):
        self.BaseDeDatos.insertarEvento(datetime.now(), evento)

    def anadirUsuario(self, usuario):
        self.BaseDeDatos.insertarUsuario(usuario)

    def existeUsuario(self, usuario):
        return self.BaseDeDatos.ExisteUsuario(usuario)

    def ExisteEvento(self, evento):
        return self.BaseDeDatos.ExisteEvento(
            evento, self.BaseDeDatos.IDUsuario(self.usuario))

    def Incrementar(self, evento):
        self.BaseDeDatos.IncrementarVeces(evento)

    def EventoFinalizado(self, e):
        self.BaseDeDatos.EventoFinalizado(e)

    def CambioUsuarioActivo(self, usuario):
        self.BaseDeDatos.cambiarUsuarioActivo(usuario)
        self.usuario = usuario

    def NingunaVez(self, e):
        self.BaseDeDatos.NingunaVeces(e)
        self.BaseDeDatos.IncrementarVeces(e)

    def UsuarioActivo(self):
        return self.BaseDeDatos.usuarioActivo()

    def EventoActivo(self, e):
        ID = self.BaseDeDatos.IDUsuario(self.usuario)
        if (e.rep):
            return self.BaseDeDatos.EventoEsActivo(
                e.med, e.fecha, ID, e.rep, e.cuando[e.cuando.index(' ') + 1:],
                int(e.cuando[:e.cuando.index(' ')]))
        else:
            return self.BaseDeDatos.EventoEsActivo(e.med, e.fecha, ID, e.rep,
                                                   None, None)

    def borrarEvento(self, e):
        print(e)
        if (e.rep):
            if (' ' in e.cuando):
                self.BaseDeDatos.borrarEvento(
                    e.med, e.fecha, e.usuario, e.rep,
                    e.cuando[e.cuando.index(' ') + 1:],
                    int(e.cuando[:e.cuando.index(' ')]))
            else:
                self.BaseDeDatos.borrarEvento(e.med, e.fecha, e.usuario, e.rep,
                                              e.cuando, '')
        else:
            self.BaseDeDatos.borrarEvento(e.med, e.fecha, e.usuario, e.rep,
                                          None, None)

    def crearRecordatorios(self, fichero):
        LEventos = self.BaseDeDatos.eventosActivos()
        for e in LEventos:
            print(e)
            if (e.rep):
                if (
                        ' ' in e.cuando.strip()
                ):  ##Se hace el strip para borrar el blanco a la derecha en las comidas
                    Repeticion = e.cuando[e.cuando.index(' ') + 1:]
                    veces = int(e.cuando[:e.cuando.index(' ')])
                else:
                    Repeticion = e.cuando.strip()

                if (not e.fecha is None):
                    fecha = e.fecha
                print(Repeticion)
                if (Repeticion == 'dia'):
                    if (not self.existe_Trabajo('Repeticion cada ' +
                                                str(veces) + ' dias,' + e.med +
                                                ',' + e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion cada ' + str(veces) + ' dias,' +
                            e.med + ',' + e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=fecha.month,
                            day=str(fecha.day) + '/' + str(veces),
                            hour=fecha.hour,
                            minute=fecha.minute,
                            replace_existing=True,
                            args=['default', e, True, self])
                elif (Repeticion == 'mes'):
                    if (not self.existe_Trabajo('Repeticion ' + str(veces) +
                                                ' meses ,' + e.med + ',' +
                                                e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion ' + str(veces) + ' meses ,' +
                            e.med + ',' + e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=str(fecha.month) + '/' + str(veces),
                            day=fecha.day,
                            hour=fecha.hour,
                            minute=fecha.minute,
                            replace_existing=True,
                            args=['default', e, True, self])
                elif (Repeticion == 'semana'):
                    if (not self.existe_Trabajo('Repeticion cada ' +
                                                str(veces) + ' dias,' + e.med +
                                                ',' + e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion' + str(veces) + ' semanas,' +
                            e.med + ',' + e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=fecha.month,
                            day=str(fecha.day) + '/' + str(7 * veces),
                            hour=fecha.hour,
                            minute=fecha.minute,
                            replace_existing=True,
                            args=['default', e, True, self])
                elif (Repeticion == 'hora'):
                    if (not self.existe_Trabajo('Repeticion ' + str(veces) +
                                                ' horas,' + e.med + ',' +
                                                e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion ' + str(veces) + ' horas,' + e.med +
                            ',' + e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=fecha.month,
                            day=fecha.day,
                            hour=str(fecha.hour) + '/' + str(veces),
                            minute=fecha.minute,
                            replace_existing=True,
                            args=['default', e, True, self])
                elif (Repeticion == 'desayuno'):  #HORA-1
                    if (not self.existe_Trabajo('Repeticion Desayuno' + ',' +
                                                e.med + ',' + e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion Desayuno' + ',' + e.med + ',' +
                            e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=fecha.month,
                            day=fecha.day,
                            hour='8/1',
                            minute=0,
                            replace_existing=True,
                            args=['default', e, True, self])
                elif (Repeticion == 'comida'):  #HORA-1
                    if (not self.existe_Trabajo('Repeticion Comida' + ',' +
                                                e.med + ',' + e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion Comida' + ',' + e.med + ',' +
                            e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=fecha.month,
                            day=fecha.day,
                            hour='13/1',
                            minute=0,
                            replace_existing=True,
                            args=['default', e, True, self])
                elif (Repeticion == 'cena'):  #HORA-1
                    if (not self.existe_Trabajo('Repeticion Desayuno' + ',' +
                                                e.med + ',' + e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion Cena' + ',' + e.med + ',' +
                            e.usuario + ',' + str(e.fecha),
                            year=fecha.year,
                            month=fecha.month,
                            day=fecha.day,
                            hour='20/1',
                            minute=0,
                            replace_existing=True,
                            args=['default', e, True, self])
                else:
                    if (not self.existe_Trabajo('Repeticion semanal cada ' +
                                                Repeticion + ',' + e.med +
                                                ',' + e.usuario + ',' +
                                                str(e.fecha))):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'cron',
                            id='Repeticion semanal cada ' + Repeticion + ',' +
                            e.med + ',' + e.usuario + ',' + str(e.fecha),
                            day_of_week=self.dia_sem(Repeticion),
                            year=fecha.year,
                            month=fecha.month,
                            day=fecha.day,
                            hour=fecha.hour,
                            minute=fecha.minute,
                            replace_existing=True,
                            args=['default', e, True, self])
                ahora = datetime.now()
                fechaE = e.fecha
                #print(str(ahora)+" y "+fechaE)
                if (ahora < fechaE and e.veces > 1):
                    if (not self.existe_Trabajo1(
                            'Evento repetitivo: recordando tomar ' + e.med +
                            ' a ' + e.usuario + ' cada ' + e.cuando)):
                        self.planificador1.add_job(
                            fichero.recordatorioTomar,
                            'interval',
                            seconds=20,
                            id='Evento repetitivo: recordando tomar ' + e.med +
                            ' a ' + e.usuario + ' cada ' + e.cuando,
                            args=[e, 'default', self])
            else:
                if (not e.fecha is None):
                    fecha = e.fecha

                ahora = datetime.now()
                fechaE = e.fecha
                #print(str(ahora)+" y "+fechaE)
                if (ahora < fechaE):
                    if (not self.existe_Trabajo(
                            str(e.fecha) + ',' + e.med + ',' + e.usuario)):
                        self.planificador.add_job(
                            fichero.recordatorio,
                            'date',
                            run_date=fecha,
                            id=str(e.fecha) + ',' + e.med + ',' + e.usuario,
                            args=['default', e, False, self])
                else:
                    if (not self.existe_Trabajo1(
                            'Evento no repetitivo:recordando tomar ' + e.med +
                            ' a ' + e.usuario)):
                        self.planificador1.add_job(
                            fichero.recordatorioTomar,
                            'interval',
                            seconds=20,
                            id='Evento no repetitivo: recordando tomar ' +
                            e.med + ' a ' + e.usuario,
                            args=[e, 'default', self])
        print('planificador')
        self.planificador.print_jobs()
        print('planificador1')
        self.planificador1.print_jobs()

    class sincronizarEventos(threading.Thread):
        def __init__(self, Snips):
            threading.Thread.__init__(self)
            self.usuario = Snips.usuario
            self.Snips = Snips

        def run(self):
            while True:
                if (self.Snips.BaseDeDatos.HayActualizados()):
                    print('Actualizando threads')
                    self.Snips.crearRecordatorios(self.Snips.fichero)
                    self.Snips.BaseDeDatos.cambioANoActualizado()
                time.sleep(5)
示例#35
0
@app.route('/SomeFunction', methods=['POST'])
def SomeFunction():
    global variably
    variably = False
    forward_message = variably
    return render_template('index.html', forward_message=forward_message)


@app.route('/funky', methods=['POST'])
def funky():
    global variably
    variably = True
    forward_message = variably
    return render_template('index.html', forward_message=forward_message)


@app.route('/monky', methods=['POST'])
def monky():
    forward_message = variably
    print(variably)
    return render_template('index.html', forward_message=forward_message)


sched.add_job(task, 'cron', id='pupil_morn', day_of_week='mon-fri', hour=7)
print('sched set')
sched.print_jobs()

if __name__ == '__main__':
    app.run(environ.get('PORT'))
示例#36
0
class Jobs_Scheduler():
    
    __lock_sending_to_msg_q = threading.Lock()
    
    def __init__(self):
        
        self.__scheduler = None
        self.__init_scheduler()
    
    def __init_scheduler(self):
        try:
            
            self.__scheduler = BackgroundScheduler()
            self.__load_scheduled_jobs()
            
        except Exception as e:
            Logger.log_debug('ERROR @ Job_Scheduler -> __init_scheduler')
            Logger.log_error(str(e))
        finally:
            Logger.log_info('Done with initializing job scheduler service')
        
    def start_scheduler(self):
        self.__scheduler.start()
    
    def stop_scheduler(self):
        self.__scheduler.stop()
    
    def __load_scheduled_jobs(self):

        try:
            file_path = cfg.SCHEDULED_JOBS_FILES_PATH

            for file in glob.glob(file_path + "*.shed"):

                dict_msg = CF.load_dictionary_object(file)

                jobid = str(dict_msg["cronjobid"])
                m = str(dict_msg["cronminute"])
                h = dict_msg["cronhour"]
                dow = dict_msg["crondateofweek"]

                self.schedule_a_job(jobid, m, h, dow, None)

        except Exception as e:
            Logger.log_debug("ERROR @ load_scheduled_jobs")
            Logger.log_error(str(e))
    
    def schedule_a_job(self, cronjobid, m="0",h='*',dow='*', message_dict=None):

        #-----------------------------------------
        # jobid format :- <device_com_pk><hub_pk>
        #-----------------------------------------
        ret_val = False
        #Jobs_Scheduler.__job_lock.acquire()
        try:

            if m>=0:

                #dict_obj={"jobid":jobid,"m":m,"h":h,"dow":dow}

                ret_val = True
                if not message_dict == None:
                    
                    file_name = '%s%s%s' % (cfg.SCHEDULED_JOBS_FILES_PATH, cronjobid , ".shed")
                    ret_val = CF.save_dictionary_object(file_name, message_dict)

                if ret_val:
                    #print 'adding a schedule'
                    Logger.log_info('Adding scheduler job ' + str(cronjobid))
                    self.__scheduler.add_job(Jobs_Scheduler.scheduler_callback_function
                                                       ,minute=m,hour=h,day_of_week=dow, id=cronjobid,trigger="cron",kwargs={"jobid":cronjobid})

            return ret_val
        except Exception as e:
            Logger.log_debug("ERROR @ schedule_a_job")
            Logger.log_error(str(e))
            return False
        finally:
            #Jobs_Scheduler.__job_lock.release()
            pass
        
    def remove_a_scheduled_job(self, cronjobid):
        #Jobs_Scheduler.__job_lock.acquire()
        try:

            Logger.log_debug("Removing scheduled job " + cronjobid)
            self.__scheduler.remove_job(cronjobid)
            file_name = cfg.SCHEDULED_JOBS_FILES_PATH + cronjobid + ".shed"
            os.remove(file_name)

            return (True,"")

        except Exception as e:
            Logger.log_debug("ERROR @ remove_a_scheduled_job")
            Logger.log_error(str(e))
            return (False,str(e).replace('u',''))
        finally:
            #Jobs_Scheduler.__job_lock.release()
            pass
        
        
    def print_jobs(self):
        try:
            self.__scheduler.print_jobs()
        
        except Exception as e:
            Logger.log_debug("ERROR @ print_jobs")
            Logger.log_error(str(e))
            
    @staticmethod
    def scheduler_callback_function(jobid):

        Jobs_Scheduler.__lock_sending_to_msg_q.acquire()
        try:
            
            jobid = str(jobid)
            
            Logger.log_info("Scheduler triggered for job "+ jobid)
            file_path = cfg.SCHEDULED_JOBS_FILES_PATH
            file_name = file_path + jobid + ".shed"

            dict_msg = CF.load_dictionary_object(file_name)

            if not dict_msg == None:

                # Send the message to MessageProc q
                result_msg = Jobs_Scheduler.send_job_command(dict_msg)
                
        except Exception as e:
            Logger.log_debug("ERROR @ scheduler_callback_function")
            Logger.log_error(str(e))

        finally:
            Logger.log_debug("End of scheduler_callback_function")
            Jobs_Scheduler.__lock_sending_to_msg_q.release()
            
            
    @staticmethod
    def send_job_command(dict_command):
        try:
            
            cronjobid = dict_command['cronjobid']
            device_code = dict_command['devicecode']
            com_id = dict_command['comid']
            hubcondeviceid = dict_command['hubcondeviceid']
            comcode = dict_command['comcode']
            
            dict_command.update({'u_o_s': 'S'})
            
            zc = ZC()
            mp_sock = zc.connect_zmq(cfg.msg_proc_ip, cfg.msg_proc_port, 15000)
            mp_sock.send(json.dumps(dict_command))
            
            ret_msg = None
            ret_msg = zc.zmq_recv(mp_sock, 15000)
            mp_sock.close()
            del mp_sock

            if not ret_msg == None:
                
                ret_msg = json.loads(ret_msg)
                # Send to notification Q
                
                hub_sno = CF.get_hub_serial_no()
                ret_msg.update({'hub_sno': hub_sno})
                ret_msg.update({'notification_type': 'CRON_EVENT'})
                ret_msg.update({'msg_type' :'NOTIFICATION'})
                ret_msg.update({'notification_dt': datetime.datetime.now().strftime("%Y%m%d %H%M%S")})
                ret_msg.update({'cronjobid': cronjobid})
                ret_msg.update({'devicecode': device_code})
                ret_msg.update({'hubcondeviceid': hubcondeviceid})
                ret_msg.update({'comcode': comcode})
                
                Logger.log_debug('Sending ack to notification queue')
                CF.send_to_notifiction_queue(ret_msg)
            else:
                Logger.log_error('No response back from the message processing queue for the scheduled event.')
            
        except Exception as e:
            Logger.log_debug("ERROR @ Jobs_Scheduler -> send_job_command")
            Logger.log_error(str(e))
    
    """
    @staticmethod
    def send_to_notifiction_queue(dict_msg):
        try:
            zc = ZC()
            en_sock = zc.connect_zmq(cfg.EVENTS_PROCESSOR_IP, cfg.EVENTS_PROCESSOR_PORT)
            en_sock.send(json.dumps(dict_msg))
            
            ret_msg = None
            ret_msg = zc.zmq_recv(en_sock)
            en_sock.close()
            del en_sock
            
            if ret_msg == None:
                return False
            else:
                return True
            
        except Exception as e:
            Logger.log_debug("ERROR @ Jobs_Scheduler -> send_to_notifiction_queue()")
            Logger.log_error(str(e))
            return False
    """
    
    
    
示例#37
0
文件: Ctl.py 项目: cbluoss/TerraCtl
                      name="sunset",
                      args=[
                          HW,
                      ])
    scheduler.add_job(func=event_disable_fog,
                      trigger=TRIGGER,
                      next_run_time=FOG_STOP_AT,
                      name="fog_stop",
                      args=[
                          HW,
                      ])
    scheduler.add_job(func=event_high_noon,
                      trigger=TRIGGER,
                      next_run_time=HIGHNOON_AT,
                      name="highnoon",
                      args=[
                          HW,
                      ])

    logging.info(scheduler.print_jobs())

    while True:
        if ENABLE_DB:
            logging.info("write state to db")
            state = State(state=HW.get_state(), date=datetime.now())
            db_session.add(state)
            logging.info("session state: ", db_session.new)
            db_session.commit()
        HW.display.refresh_image(HW.get_DHT_values())
        sleep(60)
示例#38
0
def proxy(url):
    elems = url.split('/')
    lelems = len(elems)

    if lelems > 0 and elems[0] == 'api':
        elems1 = elems[1]
        if elems1 == 'all':
            elem2 = elems[2]
            if elem2 == 'on':
                ml.on()

            elif elem2 == 'off':
                ml.off()

            elif elem2 == 'white':
                ml.set_white()

            elif elem2 == 'nightmode':
                ml.nightmode()

            elif elem2 == 'discomode':
                ml.discomode()

            elif elem2 == 'brightness':
                print(elems)
                ml.set_brightness(int(elems[3]))

            elif elem2 == 'color':
                ml.set_hex_color(elems[3])

            elif elem2 == 'hue':
                ml.set_color(elems[3])

            elif elem2 == 'transition':
                if elem[3] == 'white':
                    time = elems[4]
                    brightness = elems[5]
                    ml.whitetransition(brightness, time)

            return "ok"
        elif elems1 == 'group1':
            elem2 = elems[2]
            if elem2 == 'on':
                ml.group_on(1)

            elif elem2 == 'off':
                ml.group_on(2)

            return "ok"

        elif elems1 == 'alarm':
            time           = elems[2]
            dtalarm        = datetime.now()
            dtalarm = dtalarm.replace(hour = int(time[0:2]), minute = int(time[2:4]), second=0)

            if dtalarm < datetime.now():
                dtalarm += timedelta(days=1)

            timediff = dtalarm - datetime.now()

            apsched = BackgroundScheduler()
            apsched.start()

            print("Scheduling alarm for %s (%ss from now)" % (dtalarm, timediff.seconds))
            apsched.add_job(do_alarm, 'date', run_date=dtalarm, id='wakeup')
            apsched.print_jobs()
            ml.whitetransition(2, 5)
            ml.off()
            return "Scheduled for %s" % time


        elif elems1 == 'ip':
            ml.set_ip(elems[2])
            return "ok"
        else:
            return "not found", 404

    else:
        return serve_web(url)
示例#39
0
    else:
        print('The job worked :)')

# def my_listener1(event):
#     print(event)





# scheduler.add_job(my_job, 'interval', seconds=3)
# scheduler.start()
# while True:
#     pass

#
# scheduler.add_job(my_job, 'interval', seconds=3, start_date='2018-04-07 13:49:00', end_date='2018-04-07 17:19:00',
#                   id='my_job_id')
scheduler.add_job(my_job, 'interval', seconds=3, id='my_job_id')


scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
# scheduler.add_listener(my_listener1)

jobs = scheduler.get_jobs()
scheduler.print_jobs()
scheduler.start()
# scheduler.pause_job('my_job_id')
# scheduler.resume_job('my_job_id')
# scheduler.remove_job('my_job_id')
# scheduler.shotdown(wait=False)
示例#40
0
def add_single_backup_job(v_setup_id):  # mysql_ins_bak_setup 表的当前更新或插入的备份实例id

    os_user = config.OS_USER

    os_password = config.OS_APPS_PASSWD

    scheduler = BackgroundScheduler()  # 默认内存的jobstore

    url = "sqlite:////home/apps/dbajob.sqlite"

    scheduler.add_jobstore("sqlalchemy", url=url, alias="sqlite_js")

    scheduler.print_jobs()

    print "a"

    # 连接配置中心库,获取数据库备份周期等信息
    db = Connection("/tmp/mysql3306.sock", config.DB_NAME, config.DB_USER, config.DB_PASSWD, time_zone="+8:00")

    v_sql = r"""SELECT a.instance_id,b.ip,b.port,a.backup_interval_type,a.backup_start_time from mysql_ins_bak_setup a,tag b where 
        a.instance_id=b.id and a.id=%d""" % (
        v_setup_id
    )

    print v_sql

    bak_server = db.get(v_sql)

    instance_id = bak_server["instance_id"]

    from_host = bak_server["ip"]

    # print from_host

    mysql_port = bak_server["port"]

    backup_interval_type = bak_server["backup_interval_type"]

    backup_start_time = bak_server["backup_start_time"]

    str_start_date = time.strftime("%Y-%m-%d") + " " + backup_start_time

    print str_start_date

    v_job_id = "backup_%s_%s" % (from_host, str(mysql_port))

    if backup_interval_type == 1:  # every day

        # scheduler.add_interval_job(backup, days=1, start_date=str_start_date, args=[from_host, mysql_port, os_user, os_password], jobstore='file')

        scheduler.add_job(
            backup,
            "interval",
            id=v_job_id,
            days=1,
            start_date=str_start_date,
            args=[from_host, mysql_port, os_user, os_password],
            replace_existing=True,
            jobstore="sqlite_js",
        )

    elif backup_interval_type == 2:  # every week weeks=1

        scheduler.add_job(
            backup,
            "interval",
            id=v_job_id,
            weeks=1,
            start_date=str_start_date,
            args=[from_host, mysql_port, os_user, os_password],
            replace_existing=True,
            jobstore="sqlite_js",
        )

    elif backup_interval_type == 3:  # every hour hours=1

        scheduler.add_job(
            backup,
            "interval",
            id=v_job_id,
            hours=1,
            start_date=str_start_date,
            args=[from_host, mysql_port, os_user, os_password],
            replace_existing=True,
            jobstore="sqlite_js",
        )

    else:
        pass

    scheduler.print_jobs()

    print "b"

    scheduler.start()

    scheduler.print_jobs()

    print "c"

    # 开始在数据库记录备份的调度任务状态 0:调度任务已启动,实际备份还没有开始

    v_sche_start_sql = """insert into mysql_ins_bak_log(instance_id,backup_result_type) 
    values(%d,0)""" % (
        instance_id
    )

    db.execute(v_sche_start_sql)

    db.close()