當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。