当前位置: 首页>>代码示例>>Python>>正文


Python asyncio.AsyncIOScheduler方法代码示例

本文整理汇总了Python中apscheduler.schedulers.asyncio.AsyncIOScheduler方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.AsyncIOScheduler方法的具体用法?Python asyncio.AsyncIOScheduler怎么用?Python asyncio.AsyncIOScheduler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在apscheduler.schedulers.asyncio的用法示例。


在下文中一共展示了asyncio.AsyncIOScheduler方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: asyncio_schedule

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def asyncio_schedule():
    """
    python version >= 3.4.0
    :return:
    """
    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    try:
        import asyncio
    except ImportError:
        import trollius as asyncio

    def tick():
        print('Tick! The time is: %s' % datetime.now())

    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass 
开发者ID:tomoncle,项目名称:Python-notes,代码行数:26,代码来源:schdule.py

示例2: __init__

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def __init__(self, logger=None):
        self._user_token = None
        self._user_client = None
        self._bot_token = None
        self._bot_client = None
        self._verification_token = None
        self._executor = concurrent.futures.ThreadPoolExecutor()
        self.logger = logger or logging.getLogger("uqcsbot")
        self._handlers: DefaultDict[str, list] = collections.defaultdict(list)
        self._command_registry: DefaultDict[str, list] = collections.defaultdict(list)
        self._scheduler = AsyncIOScheduler()

        self.register_handler('message', self._handle_command)
        self.register_handler('hello', self._handle_hello)
        self.register_handler('goodbye', self._handle_goodbye)

        self.channels = ChannelWrapper(self)
        self.users = UsersWrapper(self) 
开发者ID:UQComputingSociety,项目名称:uqcsbot,代码行数:20,代码来源:base.py

示例3: before_server_start

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def before_server_start(self):
        @self._app.listener('before_server_start')
        async def initialize_scheduler(app, loop):
            self._proxy = await create_ethereumd_proxy(self.endpoint,
                                                       loop=loop)
            self._poller = Poller(self._proxy, self.cmds, loop=loop)
            self._scheduler = AsyncIOScheduler({'event_loop': loop})
            if self._poller.has_blocknotify:
                self._scheduler.add_job(self._poller.blocknotify, 'interval',
                                        id='blocknotify',
                                        seconds=1)
            if self._poller.has_walletnotify:
                self._scheduler.add_job(self._poller.walletnotify, 'interval',
                                        id='walletnotify',
                                        seconds=1)
            if self._scheduler.get_jobs():
                self._scheduler.start()
        return initialize_scheduler 
开发者ID:DeV1doR,项目名称:ethereumd-proxy,代码行数:20,代码来源:server.py

示例4: initialize_scheduler

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def initialize_scheduler(app, loop):
    # Check that tables exist
    await db.gino.create_all()

    # Schedule exchangerate updates
    try:
        _ = open("scheduler.lock", "w")
        fcntl.lockf(_.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)

        scheduler = AsyncIOScheduler()
        scheduler.start()

        # Updates lates 90 days data
        scheduler.add_job(update_rates, "interval", hours=1)

        # Fill up database with rates
        count = await db.func.count(ExchangeRates.date).gino.scalar()
        scheduler.add_job(update_rates, kwargs={"historic": True})
    except BlockingIOError:
        pass 
开发者ID:exchangeratesapi,项目名称:exchangeratesapi,代码行数:22,代码来源:app.py

示例5: apscheduler

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def apscheduler(app: web.Application) -> AsyncGenerator[None, None]:
    scheduler = AsyncIOScheduler()
    _register_in_app(app, "scheduler", scheduler)
    scheduler.start()
    yield

    if scheduler.running:
        scheduler.shutdown() 
开发者ID:pyslackers,项目名称:website,代码行数:10,代码来源:contexts.py

示例6: scheduler

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def scheduler() -> AsyncIOScheduler:
    """Thread global scheduler to handle all recurring tasks.

    If no scheduler exists yet, this will instantiate one."""

    global __scheduler

    if not __scheduler:
        try:
            __scheduler = AsyncIOScheduler(event_loop=asyncio.get_event_loop())
            __scheduler.start()
            return __scheduler
        except UnknownTimeZoneError as e:
            raise Exception("apscheduler failed to start. This is probably "
                            "because your system timezone is not set. "
                            "Set it with e.g. echo \"Europe/Berlin\" > "
                            "/etc/timezone") from e
    else:
        # scheduler already created, make sure it is running on
        # the correct loop
        # noinspection PyProtectedMember
        if not __scheduler._eventloop == asyncio.get_event_loop():
            raise RuntimeError("Detected inconsistend loop usage. "
                               "Trying to schedule a task on a new event "
                               "loop, but scheduler was created with a "
                               "different event loop. Make sure there "
                               "is only one event loop in use and that the "
                               "scheduler is running on that one.")
        return __scheduler 
开发者ID:RasaHQ,项目名称:rasa_core,代码行数:31,代码来源:jobs.py

示例7: sche

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def sche():
    scheduler = AsyncIOScheduler()
    # TODO: fit for all environments with different timezone, this is for 0 timezone
    scheduler.add_job(send_early_msg, 'cron', hour='3', minute='0')
    scheduler.add_job(send_new_day_msg, 'cron', hour='0', minute='0')
    scheduler.start() 
开发者ID:BoYanZh,项目名称:QQGroupRepeater,代码行数:8,代码来源:coolq.py

示例8: scheduler

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def scheduler() -> AsyncIOScheduler:
    """Thread global scheduler to handle all recurring tasks.

    If no scheduler exists yet, this will instantiate one."""

    global __scheduler

    if not __scheduler:
        try:
            __scheduler = AsyncIOScheduler(event_loop=asyncio.get_event_loop())
            __scheduler.start()
            return __scheduler
        except UnknownTimeZoneError:
            raise_warning(
                "apscheduler could not find a timezone and is "
                "defaulting to utc. This is probably because "
                "your system timezone is not set. "
                'Set it with e.g. echo "Europe/Berlin" > '
                "/etc/timezone"
            )
            __scheduler = AsyncIOScheduler(
                event_loop=asyncio.get_event_loop(), timezone=utc
            )
            __scheduler.start()
            return __scheduler
    else:
        # scheduler already created, make sure it is running on
        # the correct loop
        # noinspection PyProtectedMember
        if not __scheduler._eventloop == asyncio.get_event_loop():
            raise RuntimeError(
                "Detected inconsistent loop usage. "
                "Trying to schedule a task on a new event "
                "loop, but scheduler was created with a "
                "different event loop. Make sure there "
                "is only one event loop in use and that the "
                "scheduler is running on that one."
            )
        return __scheduler 
开发者ID:botfront,项目名称:rasa-for-botfront,代码行数:41,代码来源:jobs.py

示例9: cb_instantiate_scheduler

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def cb_instantiate_scheduler(app, loop):
        scheduler = AsyncIOScheduler()
        scheduler.add_job(HANDLERS.sender_loop, 'interval', seconds=1)
        scheduler.start() 
开发者ID:c0rvax,项目名称:project-black,代码行数:6,代码来源:server.py

示例10: __init__

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def __init__(self,
                 glo_setting: Dict[str, Any],
                 scheduler: AsyncIOScheduler,
                 app: Quart,
                 bot_api: Api,
                 *args, **kwargs):
        '''
        初始化,只在启动时执行一次

        参数:
            glo_setting 包含所有设置项,具体见default_config.json
            bot_api 是调用机器人API的接口,具体见<https://python-aiocqhttp.cqp.moe/>
            scheduler 是与机器人一同启动的AsyncIOScheduler实例
            app 是机器人后台Quart服务器实例
        '''
        # 注意:这个类加载时,asyncio事件循环尚未启动,且bot_api没有连接
        # 此时不要调用bot_api
        # 此时没有running_loop,不要直接使用await,请使用asyncio.ensure_future并指定loop=asyncio.get_event_loop()

        # 如果需要启用,请注释掉下面一行
        return

        # 这是来自yobot_config.json的设置,如果需要增加设置项,请修改default_config.json文件
        self.setting = glo_setting

        # 这是cqhttp的api,详见cqhttp文档
        self.api = bot_api

        # # 注册定时任务,详见apscheduler文档
        # @scheduler.scheduled_job('cron', hour=8)
        # async def good_morning():
        #     await self.api.send_group_msg(group_id=123456, message='早上好')

        # # 注册web路由,详见flask与quart文档
        # @app.route('/is-bot-running', methods=['GET'])
        # async def check_bot():
        #     return 'yes, bot is running' 
开发者ID:yuudi,项目名称:yobot,代码行数:39,代码来源:custom.py

示例11: __init__

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def __init__(self,
                 glo_setting: Dict[str, Any],
                 scheduler: AsyncIOScheduler,
                 bot_api: Api,
                 *args, **kwargs):
        self.setting = glo_setting
        self.news_interval_auto = glo_setting['news_interval_auto']
        self.spiders = Spiders()
        self.scheduler = scheduler
        self.api = bot_api
        self._rssjob = {}
        self.rss = {
            "news_jp_twitter": {
                "name": "日服推特",
                "source": "http://rsshub.app.cdn.cloudflare.net/twitter/user/priconne_redive",
                # headers: 可选,附加请求头
                "headers": {"host": "rsshub.app"},
                "pattern": "{title}\n链接:{link}",
            },
            "news_jp_official": {
                "name": "日服官网",
                "source": "http://rsshub.app.cdn.cloudflare.net/pcr/news",
                "headers": {"host": "rsshub.app"},
                "pattern": "{title}\n{link}",
            },
            "news_cn_bilibili": {
                "name": "国服B站动态",
                "source": "http://rsshub.app.cdn.cloudflare.net/bilibili/user/dynamic/353840826",
                "headers": {"host": "rsshub.app"},
                "pattern": "{title}\n{link}",
            }
        } 
开发者ID:yuudi,项目名称:yobot,代码行数:34,代码来源:push_news.py

示例12: main

# 需要导入模块: from apscheduler.schedulers import asyncio [as 别名]
# 或者: from apscheduler.schedulers.asyncio import AsyncIOScheduler [as 别名]
def main():
    args = parse_args()

    if args.debug:
        logger.setLevel(logging.DEBUG)

    scheme = 'https' if args.secure else 'http'
    status_url = '{}://{}:{}{}'.format(scheme, args.ip, args.port,
                                       args.status_path)
    health_url = '{}://{}:{}{}'.format(scheme, args.ip, args.port,
                                       args.health_path)
    eureka = EurekaClient(args.name, args.port, args.ip,
                          eureka_url=args.eureka,
                          instance_id=args.instance_id,
                          status_page_url=status_url,
                          health_check_url=health_url)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(eureka.register())
    logger.info('Registered with eureka as %s', eureka.instance_id)

    scheduler = AsyncIOScheduler({'event_loop': loop})

    @scheduler.scheduled_job(IntervalTrigger(seconds=args.interval))
    async def renew_lease():
        try:
            logger.debug('Attempting to renew the lease...')
            await eureka.renew()
            logger.info('Lease renewed')
        except EurekaException as e:
            if e.status == HTTPStatus.NOT_FOUND:
                logger.info('Lease expired, re-registering.')
                await eureka.register()
                return
            logger.error('Error performing renewal: %s', e)

    scheduler.start()
    try:
        logger.info('Running')
        with contextlib.suppress(KeyboardInterrupt):
            loop.run_forever()
    finally:
        scheduler.shutdown()
        loop.run_until_complete(eureka.deregister())
        loop.close() 
开发者ID:wasp,项目名称:eureka,代码行数:47,代码来源:__main__.py


注:本文中的apscheduler.schedulers.asyncio.AsyncIOScheduler方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。