Python trio.current_time() Examples
The following are 19
code examples of trio.current_time().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
trio
, or try the search function
.
Example #1
Source File: test_trio_utils.py From trinity with MIT License | 6 votes |
def test_every(autojump_clock): start_time = trio.current_time() every_generator = every(2, initial_delay=1) first_time = await every_generator.__anext__() assert first_time == pytest.approx(trio.current_time()) assert first_time <= trio.current_time() assert first_time == pytest.approx(start_time + 1) second_time = await every_generator.__anext__() assert second_time == pytest.approx(trio.current_time()) assert second_time == pytest.approx(first_time + 2) third_time = await every_generator.__anext__() assert third_time == pytest.approx(trio.current_time()) assert third_time == pytest.approx(first_time + 4)
Example #2
Source File: rate_limiter.py From starbelly with MIT License | 5 votes |
def _read_resets_task(self): ''' This task listens for incoming resets that indicate that a request has finished downloading and its corresponding rate limit should start. :returns: This task runs until cancelled. ''' async for url in self._reset_recv: logger.debug('Reset URL: %s', url) token = get_domain_token(url.host) limit = self._rate_limits.get(token, self._global_limit) self._add_expiry(Expiry(trio.current_time() + limit, token))
Example #3
Source File: trio_utils.py From trinity with MIT License | 5 votes |
def every(interval: float, initial_delay: float = 0, ) -> AsyncGenerator[float, Optional[float]]: """Generator used to perform a task in regular intervals. The generator will attempt to yield at a sequence of target times, defined as `start_time + initial_delay + N * interval` seconds where `start_time` is trio's current time at instantiation of the generator and `N` starts at `0`. The target time is also the value that is yielded. If at a certain iteration the target time has already passed, the generator will yield immediately (with a checkpoint in between). The yield value is still the target time. The generator accepts an optional send value which will delay the next and all future iterations of the generator by that amount. """ start_time = trio.current_time() undelayed_yield_times = ( start_time + interval * iteration for iteration in itertools.count() ) delay = initial_delay for undelayed_yield_time in undelayed_yield_times: yield_time = undelayed_yield_time + delay await trio.sleep_until(yield_time) additional_delay = yield yield_time if additional_delay is not None: delay += additional_delay
Example #4
Source File: test_trio_utils.py From trinity with MIT License | 5 votes |
def test_every_send(autojump_clock): start_time = trio.current_time() every_generator = every(2, initial_delay=1) first_time = await every_generator.__anext__() assert first_time == pytest.approx(start_time + 1) second_time = await every_generator.asend(3) assert second_time == pytest.approx(first_time + 2 + 3) third_time = await every_generator.asend(1) assert third_time == pytest.approx(second_time + 2 + 1)
Example #5
Source File: conftest.py From trinity with MIT License | 5 votes |
def get_trio_time(): def _f(): return trio.current_time() return _f
Example #6
Source File: conftest.py From trinity with MIT License | 5 votes |
def genesis_time(current_time, eth2_config): slots_after_genesis = 10 return int(current_time - slots_after_genesis * eth2_config.SECONDS_PER_SLOT)
Example #7
Source File: conftest.py From trinity with MIT License | 5 votes |
def current_time(): return trio.current_time()
Example #8
Source File: mount.py From s3ql with GNU General Public License v3.0 | 5 votes |
def after_io_wait(self, timeout): duration = trio.current_time() - self._sleep_time print("### finished I/O check (took {} seconds)".format(duration))
Example #9
Source File: mount.py From s3ql with GNU General Public License v3.0 | 5 votes |
def before_io_wait(self, timeout): if timeout: print("### waiting for I/O for up to {} seconds".format(timeout)) else: print("### doing a quick check for I/O") self._sleep_time = trio.current_time()
Example #10
Source File: resource_monitor.py From starbelly with MIT License | 5 votes |
def run(self): ''' Run the resource monitor. :returns: Runs until cancelled. ''' next_run = trio.current_time() + self._interval while True: measurement = self._measure() self._measurements.append(measurement) to_remove = set() for channel in self._channels: try: channel.send_nowait(measurement) except trio.WouldBlock: continue except trio.BrokenResourceError: to_remove.add(channel) for channel in to_remove: logger.debug('Removing closed channel') self._channels.remove(channel) sleep_time = next_run - trio.current_time() while sleep_time < 0: sleep_time += self._interval await trio.sleep(sleep_time) next_run += self._interval
Example #11
Source File: context.py From hypercorn with MIT License | 5 votes |
def time() -> float: return trio.current_time()
Example #12
Source File: rate_limiter.py From starbelly with MIT License | 5 votes |
def _get_next_expiry(self): ''' Pop an expiry off the heap. If no tokens on heap, suspend until a token is available. :returns: The next expiry. :rtype: Expiry ''' while True: if not self._expires: # If there are no pending expirations, then we wait for a new # token or a reset of an existing token. with trio.CancelScope() as cancel_scope: self._expiry_cancel_scope = cancel_scope await trio.sleep_forever() continue # Now there are definitely pending expirations. Examine the earliest # pending expiration. If it is in the past, then we pop it # immediately. If it is in the future, then sleep until its # expiration time or until somebody adds or resets a token. now = trio.current_time() expires = self._expires[0].time if expires <= now: expiry = heappop(self._expires) return expiry with trio.move_on_after(expires - now) as cancel_scope: self._expiry_cancel_scope = cancel_scope await trio.sleep_forever() continue
Example #13
Source File: test_schedule.py From starbelly with MIT License | 5 votes |
def test_event_order(): # This test is async because it relies on the Trio clock. schedule = make_schedule(1) due_future = trio.current_time() + 60 due_past = trio.current_time() - 60 due_now = trio.current_time() dues = [due_future, due_past, due_now] dues.sort() assert dues[0] == due_past assert dues[1] == due_now assert dues[2] == due_future
Example #14
Source File: test_schedule.py From starbelly with MIT License | 5 votes |
def assert_elapsed(min_=None, max_=None): ''' A context manager which asserts that its block runs within some bounded time. ''' start = trio.current_time() yield elapsed = trio.current_time() - start if min_ is not None: assert elapsed >= min_ if max_ is not None: assert elapsed <= max_
Example #15
Source File: __init__.py From starbelly with MIT License | 5 votes |
def assert_min_elapsed(seconds): ''' Fail the test if the execution of a block takes less than ``seconds``. ''' start = trio.current_time() yield elapsed = trio.current_time() - start assert elapsed >= seconds, 'Completed in under {} seconds'.format(seconds)
Example #16
Source File: monitor.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_mon(self, ident) -> Monitor: self.logger.info(f'{ident} - Waiting for a monitor...') t1 = trio.current_time() mon = await self.pool.get() # type: Monitor t2 = trio.current_time() t = t2 - t1 self.logger.info(f'{ident} - Waited {t:.3f}s') yield mon self.logger.info(f'{ident} - Releasing monitor') await self.pool.put(mon)
Example #17
Source File: monitor.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_mon(self, ident) -> Monitor: self.logger.info(f'{ident} - Waiting for a monitor...') t1 = trio.current_time() mon = await self.pool.get() # type: Monitor t2 = trio.current_time() t = t2 - t1 self.logger.info(f'{ident} - Waited {t:.3f}s') yield mon self.logger.info(f'{ident} - Releasing monitor') await self.pool.put(mon)
Example #18
Source File: monitor.py From parsec-cloud with GNU Affero General Public License v3.0 | 5 votes |
def task_exited(self, task): del self._tasks[id(task)] # def before_io_wait(self, timeout): # if timeout: # print("### waiting for I/O for up to {} seconds".format(timeout)) # else: # print("### doing a quick check for I/O") # self._sleep_time = trio.current_time() # def after_io_wait(self, timeout): # duration = trio.current_time() - self._sleep_time # print("### finished I/O check (took {} seconds)".format(duration))
Example #19
Source File: test_schedule.py From starbelly with MIT License | 4 votes |
def test_schedule_one_event_run_twice(autojump_clock, mocker, nursery): ''' Create one schedule and let it run twice. ''' sched_id = '123e4567-e89b-12d3-a456-426655440001' sched_job1_id = '123e4567-e89b-12d3-a456-426655440002' sched_job2_id = '123e4567-e89b-12d3-a456-426655440003' # This schedule runs 3 hours after the last job finishes, and it has # never run before. sched = make_schedule(1, num_units=3, timing='AFTER_PREVIOUS_JOB_FINISHED', seeds=['http://schedule.example'], tags=['schedule']) sched_doc = sched.to_doc() sched_doc['latest_job'] = None assert sched.job_count == 0 start_job_count = 0 start_job_args = None async def start_job(*args): nonlocal start_job_count nonlocal start_job_args start_job_count += 1 start_job_args = args # Set up scheduler job_send, job_recv = trio.open_memory_channel(0) db = Mock() db.get_schedule_docs.return_value = async_iter([sched_doc]) db.update_job_count.side_effect = AsyncMock() crawl_manager = Mock() crawl_manager.get_job_state_channel.return_value = job_recv crawl_manager.start_job.side_effect = start_job scheduler = Scheduler(db, crawl_manager) nursery.start_soon(scheduler.run) assert crawl_manager.start_job.call_count == 0 # If we send job status for a job that isn't part of a schedule, it # should be ignored. await job_send.send(JobStateEvent( 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', None, RunState.RUNNING, datetime.fromtimestamp(trio.current_time()))) # The job should run after 60 seconds. await trio.sleep(60.5) assert start_job_count == 1 assert start_job_args[0].startswith('Test Job @') assert start_job_args[1] == ['http://schedule.example'] assert start_job_args[2] == ['schedule'] assert start_job_args[4] == '123e4567-e89b-12d3-a456-426655440001' # If we send completion status for a job that doesn't run at regular # intervals, it should be ignored. await job_send.send(JobStateEvent(sched_job1_id, sched_id, RunState.COMPLETED, datetime.fromtimestamp(trio.current_time()))) # Then it should run again three hours later. await trio.sleep(3 * 60 * 60 + 1) assert start_job_count == 2 # Remove the schedule and ensure that it does not run again. scheduler.remove_schedule(sched.id)