<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def pop_events(self, regex_pattern, timeout):
 """Pop events whose names match a regex pattern. If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout. Results are sorted by timestamp in ascending order. Args: regex_pattern: The regular expression pattern that an event name should match in order to be popped. timeout: Number of seconds to wait for events in case no event matching the condition exits when the function is called. Returns: Events whose names match a regex pattern. Empty if none exist and the wait timed out. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling. queue.Empty: Raised if no event was found before time out. """

        if not self.started:
            raise IllegalStateError(
                "Dispatcher needs to be started before popping.")
        deadline = time.time() + timeout
        while True:
            #TODO: fix the sleep loop
            results = self._match_and_pop(regex_pattern)
            if len(results) != 0 or time.time() > deadline:
                break
            time.sleep(1)
        if len(results) == 0:
            raise queue.Empty('Timeout after {}s waiting for event: {}'.format(
                timeout, regex_pattern))

        return sorted(results, key=lambda event: event['time'])