A container time isolation control system and method based on service-level switches and namespaces
By publishing time change messages to the message queue in the distributed container cluster, correcting the time acquisition function of the service process, and linking with the timer scheduling component, the problem of modifying the time of the target service process in the distributed container cluster is solved, and time unification and timer scheduling state alignment are achieved.
Patent Information
- Application Number
- CN202611618721.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-10-20
- Publication Date
- 2026-11-17
AI Technical Summary
In a distributed container cluster, it is not possible to uniformly modify the time of the target service process without affecting the host machine and non-target containers, and the persistent timer scheduling cursor cannot be aligned with the new time axis after the time jump.
By publishing time change messages to the message queue, the service processes in each target container receive and correct the return value of the time acquisition function, and the timer scheduling component corrects the scheduling cursor under mutual exclusion protection, thereby achieving process-level time isolation control and automatic alignment of timer scheduling states.
It enables unified time modification of target service processes without altering the host machine clock, and ensures that the timer scheduling state is aligned with the new timeline after the time jump, thus avoiding issues such as missed task execution or inconsistent scheduling states.
Smart Images

Figure CN123123423A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of distributed system technology, and in particular to a container time isolation control system and method based on service-level switches and namespaces. Background Technology
[0002] Distributed services typically run as multiple independent processes and are deployed in containers using a container orchestration platform. Service instances are distributed across different nodes, and the number of instances dynamically changes with the load. Time-limited business testing requires uniformly modifying the time perceived by multiple service processes. Traditional methods of modifying the host system clock affect other containers and infrastructure on the same node, and it is difficult to isolate modifications to only the target test environment in clusters across nodes, services, and replicas. Integrating injectable clock interfaces on a per-service basis requires significant modifications and cannot transparently overwrite existing code that already uses standard time functions. Furthermore, simply replacing the current time read result without correcting the persistent scheduling cursor of the timer service means that the scheduler continues scanning along the old timeline after a time jump, leading to missed task executions or inconsistencies between the scheduling state and the new time. Therefore, a technical solution is needed that can uniformly modify the time of target service processes in a distributed container cluster without modifying the host clock, and correct the timer scheduling state after a time jump. Summary of the Invention
[0003] To address the shortcomings of existing technologies where distributed container clusters cannot uniformly modify the time of target service processes without affecting the host machine and non-target containers, and where persistent timer scheduling cursors cannot be aligned with the new timeline after a time jump, this application provides a container time isolation control system and method based on service-level switches and namespaces. This method publishes time change messages to a message queue, which are received by service processes within multiple target containers. Within each process, the return value of the time acquisition function is corrected to the time obtained by adding an offset to the underlying real time. After the replacement is completed, a time change callback is used to link the timer scheduling component to correct the scheduling cursor under mutual exclusion protection, thus achieving process-level time isolation control and automatic alignment of timer scheduling states. Specifically, this application provides the following technical solutions: Firstly, this application provides a container time isolation control method based on service-level switches and namespaces, including: A time change message carrying the target time is published to a message queue, and the time change message is received by the service processes in multiple target containers respectively. Each service process determines the time offset based on the target time and the current real time, and corrects the return value of the time acquisition function to the time obtained by superimposing the time offset on the underlying real time, so that the service process obtains the replacement time as the real time progresses; After the time acquisition function is replaced, the time change callback registered in the service process is triggered; The timer scheduling component responds to the time change callback by performing cursor correction, which includes: reading the replaced time under mutual exclusion protection; adjusting the first scheduling cursor to the replaced time; and when the second scheduling cursor exceeds the replaced time, rolling back the second scheduling cursor to the replaced time, so that the existing timer continues to execute along the new time axis.
[0004] Optionally, it also includes: Each service process reads the configuration values of service-level switches and the namespace configuration bound to it during the startup phase; With the service-level switch enabled and the namespace configured, a broadcast consumer for the message queue is created and subscribed to the message topic corresponding to the namespace. The time change message is broadcast to the service processes that subscribe to the message topic through the message queue. Service processes that have not enabled the service-level switch or have not configured the namespace do not receive the time change message. Each service process also performs an idempotency check based on the message identifier carried in the time change message and discards duplicate time change messages.
[0005] Optionally, publishing the time change message includes: Receive a time modification request initiated by a client, the time modification request carrying the target time; The target time is parsed and validated for its format, and after the validation is passed, a time change message carrying the target time is constructed. The time change message is published to the message topic bound to the namespace in the message queue; After receiving a successful publication confirmation response from the message queue, the system returns the operation result to the client. If the publication fails or the confirmation response is not received within the preset timeout period, a retry is performed, and an operation failure response is returned after the number of retries is exhausted.
[0006] Optionally, determining the time offset and correcting the return value of the time acquisition function includes: The current real time is read using the underlying time function that has not been replaced; The time offset is determined based on the target time and the current real time, and the time offset is written into the memory space of the service process through atomic operations; The return value of the time acquisition function is corrected by the time offset so that the replaced return value advances synchronously with the current real time.
[0007] Optionally, triggering the time change callback includes: Arrange the registered time change callbacks in the service process into a callback list according to the registration order, and iterate through the callback list; Each time change callback in the callback list is executed synchronously in sequence, and the replaced time is passed to each time change callback. If any time change callback fails or times out, log an error and continue executing the remaining time change callbacks in the callback list.
[0008] Optionally, it also includes: The timer scheduling component persistently stores the timer body and time slot index in shared storage; The timer scheduling component reads the time slots that should be processed from the shared storage at a preset period and sends expiration messages to the timers that are expiring in the time slots. During the scheduling process, the timer scheduling component acquires a distributed lock through the mutual exclusion mechanism in the shared storage and releases the distributed lock after the current scheduling is completed, so as to ensure that the scheduling is carried out by a single instance.
[0009] Optionally, the timer scheduling component performs scheduling including: In normal scheduling, the first scheduling cursor is updated to the end time of the latest time slot processed in this scheduling. The unprocessed historical expiration time slots are determined according to the second scheduling cursor, and the historical expiration time slots are scanned and executed slot by slot starting from the position indicated by the second scheduling cursor. After processing each historical expiration time slot, the second scheduling cursor is pushed forward one step, and if the current scheduling fails, the second scheduling cursor is stopped at the earliest failed time slot. When the number of historical expired time slots processed in this scheduling reaches the preset depth limit, the scanning is paused, and the remaining historical expired time slots are retained for processing in the next scheduling.
[0010] Optionally, it also includes: Each service process receives a recovery message broadcast by the message queue, the recovery message carrying an empty target time; Remove the replacement of the time acquisition function within the process and clear the time offset, so that the service process can resume using the real system time; The time change callback registered in the service process is triggered again, and the timer scheduling component responds to the time change callback to correct the first scheduling cursor and the second scheduling cursor with the restored real current time.
[0011] Secondly, this application provides a container time isolation control system based on service-level switches and namespaces, including: The time message publishing module is used to publish a time change message carrying the target time to the message queue. The time change message is received by the service processes in multiple target containers respectively. The time replacement module is deployed in the service process within each target container. It is used to determine the time offset based on the target time and the current real time, and to correct the return value of the time acquisition function to the time obtained by adding the time offset to the underlying real time. The change callback module is used to trigger the registered time change callback after the time acquisition function is replaced; The cursor correction module is used to perform cursor correction in response to the time change callback. The cursor correction includes: adjusting the first scheduling cursor to the replacement time under mutual exclusion protection, and rolling back the second scheduling cursor to the replacement time when the second scheduling cursor exceeds the replacement time.
[0012] Thirdly, this application provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the above-described method.
[0013] The beneficial effects of this application are as follows: 1. By publishing time change messages to a message queue and having them received by service processes within multiple target containers, it is possible to uniformly modify the time of target service processes in a distributed container cluster without modifying the host machine clock. 2. By correcting the return value of the time acquisition function in each service process to the time obtained by adding the offset to the underlying real time, the modified time can be obtained transparently without modifying the existing business code one by one. 3. By linking the time change callback with the timer scheduling component, the scheduling cursor is corrected under mutual exclusion protection, so that the persistent timer continues to execute along the new time axis, avoiding the problem of inconsistency between the scheduling state and the business time after the time jump. Attached Figure Description
[0014] Figure 1 This is a flowchart illustrating the container time isolation control method provided in an embodiment of this application.
[0015] Figure 2 This is a schematic diagram of the overall architecture of the container time isolation control system provided in the embodiments of this application.
[0016] Figure 3 This is a schematic diagram of the module architecture of the container time isolation control system provided in the embodiments of this application. Detailed Implementation
[0017] To make the objectives, technical solutions, and advantages of this application clearer, the technical solutions of this application will be clearly and completely described below in conjunction with the accompanying drawings and specific embodiments. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of them. Based on the embodiments in this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
[0018] Furthermore, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature. In the description of this application, "multiple" means two or more, unless otherwise explicitly specified.
[0019] The container time isolation control method and system provided in this application are applicable to containerized deployment scenarios under a distributed microservice architecture. The method can run in service clusters deployed based on container orchestration platforms (such as Kubernetes), and is also applicable to distributed service environments based on virtual machine orchestration or hybrid orchestration. The system can be deployed on computing devices with container runtime environments, such as cloud server clusters, physical machine clusters, and edge computing nodes, and can also be deployed in infrastructures at different stages, such as development and testing environments, pre-release environments, and production environments. The container orchestration platform is used to manage the lifecycle, resource allocation, and network communication of service instances. Service instances run as containers in each worker node of the cluster, and the number of instances can elastically scale with the business load.
[0020] In distributed container clusters, time-limited business testing scenarios require uniformly modifying the time perceived by multiple service processes. For example, a flash sale on an e-commerce platform needs to uniformly advance the times of multiple microservices, such as the activity service, product service, and timer service, to the start time of the activity to verify the correctness of the business logic. Based on this, this application provides a container time isolation control method based on service-level switches and namespaces.
[0021] Example 1: like Figure 1 As shown, the container time isolation control method provided in this embodiment includes the following steps: S100, a time change message carrying the target time is published to the message queue, and the time change message is received by the service processes in multiple target containers respectively.
[0022] like Figure 2As shown, the overall system architecture of this embodiment includes a client, a time control service, a message queue, and multiple business containers and a timer management service deployed on a container orchestration platform. Each service maintains timer data and scheduling cursors through shared persistent storage. The client serves as the operation entry point for testers and can be a command-line tool, a web management interface, or an API call script. The time control service, as a unified entry point, receives time modification requests and is responsible for parameter verification and message construction, and is deployed in the cluster as an independent microservice. The message queue, as middleware for asynchronous message communication, is responsible for reliably distributing time change messages to each target service process. The shared persistent storage is used to store timer body data and scheduling cursor states, and can be implemented using storage engines such as Redis, MySQL, or MongoDB.
[0023] The client initiates a time modification request to the time control service through the debugging interface. The request carries a target time, which can be in the standard time representation of year-month-day hour:minute:second, for example, it can be set to "2026-01-15 10:00:00".
[0024] In this embodiment, the recovery request carries an empty target time, indicating a return to the actual system time. Upon receiving the request, the time control service performs format parsing and business validation on the target time. The format parsing verifies whether the time string conforms to a predefined date and time format, and the business validation checks whether the target time is within the allowed time range, typically set to no more than 365 days.
[0025] After successful verification, the time control service constructs a unified time change message. This message includes a target time field and an operation type identifier. A non-empty target time field indicates that the target time has been set; an empty field indicates that the real time has been restored. Additionally, the time change message may include auxiliary fields such as a unique message identifier, a sending timestamp, and a namespace identifier. The unique message identifier is used for message deduplication and tracking, the sending timestamp records the message's dispatch time, and the namespace identifier identifies the isolation domain to which the message belongs.
[0026] It should be noted that the time control service publishes the time change message to a designated topic in the message queue. In this embodiment, the message queue adopts a publish-subscribe pattern, which can be implemented using message middleware such as RocketMQ, Kafka, or RabbitMQ. In this embodiment, the designated topic of the message queue is bound to a namespace, and different namespaces correspond to different message topics or message tags, thereby achieving isolated message distribution.
[0027] When a broadcast consumer is created, it registers its consumer instance information with the message queue, including the consumer group name, instance identifier, and a list of subscribed topics. The consumer group name is generated by concatenating the service name and namespace identifier, with an exemplary format of "service name-namespace identifier-faketime", ensuring that consumer groups of different services and different namespaces are isolated from each other.
[0028] In this embodiment, the broadcast consumer maintains a long connection with the message queue and keeps the connection active through a heartbeat mechanism; the heartbeat interval can be set to 30 seconds, and when the message queue does not receive a heartbeat from a consumer instance for 3 consecutive heartbeat cycles, the instance is removed from the consumer group.
[0029] When a service process shuts down normally, the broadcast consumer executes a shutdown procedure, which involves sending a deregistration request to the message queue and releasing connection resources after all received but unprocessed messages have been processed. During the startup phase, each service process within the target container creates a broadcast consumer and subscribes to the topic. The broadcast consumer ensures that every instance within the same consumer group receives every message. The time change message is broadcast to each service process subscribed to the corresponding namespace; service processes not subscribed to that namespace will not receive the message.
[0030] It should be noted that the target container is determined through service-level switches and namespace configuration. Each service instance is configured with a service-level switch, named enableFakeTime here. The value of this switch is a boolean, where true indicates that the time modification function is enabled, and false indicates that it is disabled.
[0031] In this embodiment, the service-level switch can be set via configuration files, environment variables, or a configuration center, supporting dynamic switching without restarting the service. Only service instances with the service-level switch enabled and configured with message queue addresses, authentication information, and namespaces participate in time modification. The namespace is used to logically group service instances, and service instances within the same namespace share the same time modification strategy.
[0032] For example, when four types of services—Activity Service, Product Service, Email Service, and Timer Management Service—are deployed in the cluster, with each service running three replicas (a total of 12 service instances), if the service-level switch is enabled only for the Activity Service and Timer Management Service and the namespace is configured as "test-env-01," then only these six service instances will receive the time change message. The remaining six service instances will have their enableFakeTime set to false or will not have a namespace configured, and will not participate in time modification; their perceived time will still be the real system time. This design limits the impact of time changes to the explicitly enabled target process, without modifying the container orchestration platform node or the host system clock, and without affecting other containers running on the same node.
[0033] It should be noted that the message queue employs at least-once delivery semantics when transmitting time change messages, ensuring that each target service process receives the message. The message queue assigns a globally unique message identifier to each message. Upon receiving a message, each service process uses this message identifier to perform an idempotency check, preventing the same time change message from being processed repeatedly due to network retransmissions.
[0034] For example, the service process maintains a set of message identifiers in memory with a sliding window of 60 seconds. Upon receiving a message, it first checks whether the message identifier already exists in the set. If it already exists, the message is discarded; otherwise, the message identifier is added to the set and a time replacement process is executed. The size of the sliding window is set according to actual needs; 60 seconds is used as an example.
[0035] The time change message is transmitted in the message queue in a serialized structured data format, specifically JSON. The complete field structure of the message includes: a target time field, representing the target time value in UTC timestamp format; a non-empty value indicates setting the target time, while an empty string indicates restoring the real time; a message unique identifier field, generating a globally unique value using UUID format; a sending timestamp field, recording the UTC timestamp of the message's transmission; a namespace identifier field, marking the isolation domain name to which the message belongs; and an operation sequence number field, a monotonically increasing integer value used by each service process to determine the message's timing relationship. When a message with an operation sequence number less than the already processed sequence number is received, the message is discarded to avoid out-of-order processing.
[0036] For example, a message that sets a target time can be represented as follows: the target time is "2026-01-15T10:00:00Z", the message unique identifier is "msg-a1b2c3d4", the sending timestamp is "2026-01-10T10:00:00Z", the namespace identifier is "test-env-01", and the operation sequence number is 1.
[0037] The time control service employs a synchronous confirmation mechanism when publishing time change messages, waiting for a confirmation response from the message queue before returning the operation result to the client. If the message queue returns a publication failure message or fails to return a confirmation response within a preset timeout period, the time control service executes retry logic, for example, retrying up to 3 times with a 1-second interval between each retry. If the publication is still unsuccessful after the retries are exhausted, the time control service returns an operation failure error response to the client and records an alarm log. This synchronous confirmation mechanism ensures that the time change message has been reliably received by the message queue when the client receives the operation success response.
[0038] The time control service maintenance operation log records complete information for each time modification request, including the client identifier of the request source, the target time value, the namespace identifier, the operation timestamp, and the operation result. The operation log is used to audit the historical record of time modification operations, allowing operations personnel to trace time modification operations at specific points in time and their impact scope. For example, operations personnel can query the operation log to confirm all time modification and recovery operations performed on a specific namespace within a specified time period.
[0039] The linkage mechanism between the service-level switch and the configuration center allows for dynamic adjustment of the time modification function's activation and deactivation at runtime. When a tester changes `enableFakeTime` from `false` to `true` on a service instance via the configuration center, the service instance detects the switch change during the next configuration refresh cycle, automatically creates a message queue broadcast consumer, subscribes to the corresponding namespace topic, and begins receiving subsequently published time change messages. When `enableFakeTime` is changed from `true` to `false`, the service instance deregisters the message queue consumer and stops receiving time change messages; if it is currently in a time modification state, it automatically executes the recovery process. The configuration refresh cycle is, for example, 5 seconds.
[0040] The system supports parallel operation across multiple namespaces. Time modification operations between different namespaces are independent and do not affect each other.
[0041] For example, when both namespaces "test-env-01" and "test-env-02" exist in the cluster, the target time is set to 10:00:00 on January 15, 2026 for "test-env-01" and to 08:00:00 on March 1, 2026 for "test-env-02". The service processes in the two namespaces use their respective target times without interfering with each other.
[0042] The isolation of namespaces is achieved through the topic or tag mechanism of message queues. Each namespace corresponds to an independent message topic or message tag, and the service process only subscribes to the topic or tag of its own namespace.
[0043] In another implementation, the time change message can also be distributed in a targeted manner through a point-to-point message queue in conjunction with a service discovery mechanism. The time control service filters the list of instances that enable time modification based on the service registry and pushes them one by one, which can also achieve isolation control of the target service process.
[0044] S200, each of the service processes determines the time offset based on the target time and the current real time, and corrects the return value of the time acquisition function to the time obtained by superimposing the time offset on the underlying real time, so that the service process obtains the replacement time as the real time progresses.
[0045] Upon receiving the time change message, the service processes within each target container extract the target time field and determine if it is null. If the target time is not null, the time setting process begins; if the target time is null, the recovery process begins. In the time setting process, the message processor reads the current real time that has not been replaced through the underlying real time function. The underlying real time function is a function that bypasses any installed time replacement logic and directly accesses the underlying time interface of the operating system or runtime environment, ensuring that the obtained time is not affected by previous replacement operations.
[0046] The time offset is determined by using the difference between the target time and the current real time as the time offset.
[0047] For example, when the target time is 10:00:00 on January 15, 2026, and the current real time is 10:00:00 on January 10, 2026, the time offset is positive 5 days, or 432,000 seconds, indicating that the business time is advanced 5 days into the future. When the target time is 10:00:00 on January 5, 2026, the time offset is negative 5 days, or -432,000 seconds, indicating that the business time is rolled back 5 days into the past. The time offset is stored as an integer in the process's memory space, and the offset value is read and added together when the time acquisition function is called subsequently.
[0048] After determining the time offset, the message processor performs a runtime replacement on the standard time acquisition function within the process. When the replaced time acquisition function is called, it reads the underlying, unreplaced real current time and adds the time offset as the return value.
[0049] For example, when the real current time advances to 10:00:05 on January 10, 2026, the replaced time retrieval function reads this real time, adds an offset of 432,000 seconds, and returns 10:00:05 on January 15, 2026. When the real current time advances to 10:05:00 on January 10, 2026, the replaced time retrieval function returns 10:05:00 on January 15, 2026. Thus, the replaced time monotonically advances with the real time, and the flow of time is consistent with the real time, with only the starting point shifting. The replaced time can normally participate in operations such as validity period comparison, timestamp generation, and timeout judgment in business logic.
[0050] It should be noted that, in the Go language implementation, the time acquisition function is the standard library's `time.Now`. The framework registers time replacement logic when the process starts, and performs a runtime replacement on `time.Now` upon receiving a time change message. Internally, the replacement function uses the unreplaced runtime time interface as a baseline and adds the time offset. The runtime time interface is the underlying time acquisition mechanism provided by the Go runtime and is unaffected by the application-layer `time.Now` replacement. Since the business code originally directly called `time.Now` to get the current time, the modified time can be transparently obtained without modifying each business module individually after the replacement.
[0051] For example, the code in the activity service that determines whether an activity has started calls time.Now to get the current time and compares it with the activity start time. After the comparison, the call automatically returns the time after the offset. The activity service can simulate the business behavior at the start of the activity in the test environment without any code modification.
[0052] The runtime replacement mechanism is based on function pointer redirection. In the Go language implementation, the general application framework replaces the function reference of `time.Now` with the framework's internal proxy function `fakeTimeNow` during startup. The execution logic of the proxy function `fakeTimeNow` is as follows: it reads the current offset value; if the offset is zero, it directly calls the underlying runtime time interface to return the real time; if the offset is not zero, it calls the underlying runtime time interface to obtain the real current time, adds the offset, and returns it. The execution overhead of the proxy function is, for example, on the order of nanoseconds, and its performance impact on business code is negligible. Since the proxy function directly passes through the underlying time when the offset is zero, service processes that do not enable time modification will not incur additional time processing overhead even if the general application framework is loaded.
[0053] In this embodiment, the time replacement setting establishes security boundary constraints to prevent abnormal parameters from causing abnormal system behavior. These security boundaries include: a maximum offset limit, exemplarily set to ±365 days (i.e., ±31,536,000 seconds); target times exceeding this range are rejected by the message processor and an alarm log is recorded. An offset change frequency limit is also included, here set to a maximum of 10 offset changes accepted by the same service process within 60 seconds; change requests exceeding this frequency are delayed to avoid frequent time source switching causing business logic chaos. The parameter values of these security boundaries are set according to actual needs.
[0054] It should be understood that the replacement is process-level; each service process independently maintains its own time offset, without changing the host clock, and does not require containers to have permission to modify the system clock. Different containers on the same node can be configured with different namespaces, thereby using different target times or maintaining the real time, achieving process-level time isolation.
[0055] When the time is set again, the message processor redetermines the time offset with the new target time and updates the offset value of the replacement function.
[0056] For example, when the previous target time was January 15, 2026, 10:00:00, and the new target time is February 1, 2026, 10:00:00, the message processor rereads the current real time and redetermines the offset based on the new target time. The offset value of the replacement function is atomically updated, and subsequent calls to `time.Now` immediately return the time based on the new offset. After the recovery message arrives, the replacement of the time acquisition function within the process is removed, and the time offset is cleared, allowing the service process to resume using the real system time. The removal operation restores the implementation of `time.Now` to the original standard library implementation, and the clearing operation resets the offset value to zero.
[0057] The storage and retrieval of the time offset employ atomic operations to ensure concurrency safety. In a multi-threaded or multi-coroutine runtime environment, multiple execution threads of the business code may simultaneously call the time retrieval function, while the message processor may update the offset value in another thread. These atomic operations ensure that the writing and reading of the offset do not involve any partially updated intermediate states.
[0058] For example, in the Go language implementation, the time offset is stored as an int64 type, written using atomic.StoreInt64, and read using atomic.LoadInt64, ensuring atomicity on a 64-bit system. In the Java language implementation, the time offset can be stored using the AtomicLong type, with atomic read and write operations achieved through its set and get methods.
[0059] The replacement time acquisition function maintains the same time precision as the original time function. For example, in a Go language implementation, time.Now returns a time precision in the nanosecond range, and the replaced time acquisition function also returns a time value with nanosecond precision.
[0060] It should be noted that although the time offset is illustrated in seconds, it is actually stored and calculated in nanoseconds in the actual implementation to ensure that the replaced time is identical in precision to the original time. The monotonic progression of the replaced time guarantees the orderliness of the timestamps. Without any rollback of the underlying real time, the return value obtained from calling the time acquisition function at different times increases sequentially, satisfying the business logic's dependency on the orderliness of time.
[0061] The time replacement applies to all code paths within the current service process. Regardless of whether the business code calls the time retrieval function directly, through a wrapper, or internally through a third-party library, the replaced time value will be returned uniformly.
[0062] For example, in the Go language implementation, the third-party HTTP client library internally calls `time.Now` to determine request timeout. After the replacement, the library also uses the offset time for timeout determination, without requiring modification to the third-party library. The coverage of the process-level replacement allows both existing business code and third-party dependency libraries to transparently use the modified time.
[0063] After the recovery process is completed, the service process enters an unmodified time state. In this state, the proxy function `fakeTimeNow` detects that the offset is zero and directly calls the underlying runtime time interface to return the real time, without performing the offset overlay operation. Upon receiving a new setting request, the message processor re-enters the time setting process. The time replacement processor maintains a status flag recording whether the current service process is in a modified or unmodified time state. This flag is set to the modified time state after the setting process is completed and to the unmodified time state after the recovery process is completed. Business components can determine whether the current service process is in time modification mode by querying the status flag.
[0064] In another embodiment, the replacement of the time acquisition function can also be achieved through compile-time instrumentation. During the compilation phase, the call point of the standard time acquisition function is replaced with a proxy function containing offset logic, thus achieving process-level time source replacement. In an alternative embodiment, for services implemented in Java, Java Agent bytecode enhancement technology can be used to intercept and replace time acquisition methods such as System.currentTimeMillis and Instant.now during the class loading phase; this is not limited to this approach.
[0065] S300, after the time acquisition function is replaced, the time change callback registered in the service process is triggered.
[0066] After replacing the time acquisition function, the time replacement processor enters the callback triggering phase. The time replacement processor maintains a time change callback list, which is an ordered collection of function references arranged in registration order. During the initialization phase, each business component registers its callback function with the time replacement processor. Each callback item is associated with a callback function reference, its component identifier, and its registration priority. The registration process is completed during the dependency injection phase when the service process starts, by calling the registration interface provided by the time replacement processor to add the callback function to the callback list.
[0067] For example, the timer scheduling component registers a callback function named "onTimeChanged" upon startup, the cache refresh component registers a callback function named "onTimeCacheRefresh", and the log rotation component registers a callback function named "onTimeLogRotate".
[0068] After the time acquisition function is replaced, the time replacement processor traverses the callback list in the registration order and executes each callback function synchronously in sequence. Each callback function receives the current replaced time value and the operation type (set or restore) as parameters when it is called. The callback mechanism decouples the general time replacement capability from the timeline state correction of specific components: the general framework is only responsible for switching the time source and triggering callback notifications, while business components such as timer scheduling components and caching components are responsible for correcting their own time-related derived states in persistence or caching through their respective registered callback functions.
[0069] In this embodiment, the execution of the time change callback adopts a fault-tolerant isolation mechanism. The execution of each callback function is wrapped in an independent exception handling context. If the execution of a single callback function fails (throws an exception or times out), only an error log is recorded. This does not block the continued execution of other callbacks, nor does it affect the replacement result of the time acquisition function.
[0070] For example, when there are 3 callback functions registered in the callback list, corresponding to the cache refresh component, the timer scheduling component, and the log cutting component respectively, if the callback execution of the cache refresh component throws a database connection timeout exception, the time replacement processor captures the exception and records the error log, and then continues to execute the callback functions of the timer scheduling component and the log cutting component, without affecting the overall time replacement process.
[0071] In addition, components that require strong consistency processing (such as timer scheduling components) can complete the correction using mutual exclusion protection and persistent verification inside the callback function, and their internal exception handling and retry logic are independent of the callback traversal process of the time replacement processor.
[0072] It should be noted that the time replacement processor ensures that the replacement of the time acquisition function has been fully effective before triggering the callback. Internally, the time replacement processor maintains a completion semaphore. This semaphore is released after both the offset update and function replacement are complete. The callback triggering logic then begins traversing the callback list after acquiring the semaphore. The timing guarantee ensures that each callback function, when calling the time acquisition function during execution, obtains the replaced time value, not the old value before replacement.
[0073] For example, when the callback function of the timer scheduling component performs cursor correction, it needs to read the current time after replacement, and the timing guarantee ensures that the read operation returns the new time after the offset is added.
[0074] The callback mechanism supports dynamic registration and deregistration. During service process execution, business components can register new callback functions or deregister existing callback functions with the time replacement processor at any time. Registration and deregistration operations are protected by read-write locks to ensure that the callback list is not concurrently modified during traversal execution. The dynamic registration capability allows pluggable business components to automatically integrate the time change notification mechanism when loaded on demand.
[0075] Each callback function has an independent timeout limit, assumed to be 30 seconds. When the execution time of a callback function exceeds this timeout limit, the timeout processor interrupts the execution of that callback function, records a timeout error in the log, and then continues execution of the next callback function. The value of the timeout limit is set according to actual needs, for example, within the range of 5 to 60 seconds (30 seconds in this embodiment). This timeout mechanism prevents a single callback function from occupying the callback execution thread for an extended period due to deadlock or network congestion, thus affecting the timely execution of subsequent callback functions.
[0076] After the callback traversal is completed, the time replacement processor outputs a callback execution summary log. The summary log records the total number of callbacks triggered in this callback, the number of successful executions, the number of failures, and the number of skips, as well as the component identifier and exception information for each failed callback.
[0077] For example, when there are 5 callback functions registered in the callback list, of which 4 execute successfully and 1 is interrupted due to timeout, the summary log records: Total callbacks 5, 4 successful, 1 failed (Component ID: Cache preheating component, Exception: Execution timeout 30 seconds). The summary log provides a diagnostic basis for operations and maintenance personnel to troubleshoot time-related issues.
[0078] The execution order of the callback list remains stable after it is determined during the registration phase. When there are dependencies between callback functions registered by multiple business components (for example, the callback of a timer scheduling component depends on the prerequisite that time replacement has been completed), the position of the callback function in the list is controlled by the registration priority to ensure that the dependent callback is executed before the dependent one. The registration priority is represented by an integer value, with smaller values indicating higher priority. It can be set in the range of 0 to 100. Callback functions with the same priority are arranged according to their registration time.
[0079] In another implementation, the time change callback can also be implemented using an event listener pattern. Each component registers a listener for the time change event with the event bus. After the time replacement is completed, the event bus asynchronously notifies each listener to perform state correction, thus achieving decoupling between time replacement and state correction. In an alternative implementation, a publish-subscribe pattern can be used to build a lightweight event channel within the process. Each component subscribes to a time change event topic and sends an event message to that topic after the time replacement is completed.
[0080] S400, the timer scheduling component responds to the time change callback by performing cursor correction: reading the replaced time under mutual exclusion protection; adjusting the first scheduling cursor to the replaced time; when the second scheduling cursor exceeds the replaced time, rolling back the second scheduling cursor to the replaced time, so that the existing timer continues to execute along the new time axis.
[0081] The timer scheduling component persistently stores the timer body and time slot index in shared storage. The data structure of the timer body includes at least the following fields: timer identifier, used to uniquely identify each timer instance; execution time, indicating the expected time point when the timer is to be triggered; callback message information, including the target address and message content of the message to be sent after triggering; and repeat execution attribute, indicating whether the timer is periodically executed and the execution interval.
[0082] For example, the ontology data of an expiration reminder timer may include: the timer identifier is "timer-20260115-001", the execution time is January 15, 2026, 12:00:00, the callback message is the expiration notification sent to the activity service, and the repeat execution attribute is non-repeating.
[0083] The time slot index locates timers based on their execution time. The time slot index divides the time axis into consecutive time slots with a fixed granularity. Each time slot corresponds to a time interval, and all timers expiring within that time interval are indexed into the same time slot. For example, when the index is built with a granularity of 1 second, all timers expiring between 12:00:00 and 12:00:01 on January 15, 2026, are indexed into the same time slot. The time slot index enables the scheduler to quickly locate the time slot corresponding to the current time and retrieve all expiring timers within that slot in batches, avoiding the need to scan all timer data one by one.
[0084] The scheduler triggers scheduling at a preset period, assuming a tick every 1 second. Each tick reads the current time slot to be processed from shared storage, retrieves all expiring timers within that slot, and sequentially sends an expiration message to the callback address specified for each timer. In multi-instance deployment scenarios, multiple timer management service instances may attempt to execute ticks simultaneously. To prevent the same time slot from being processed repeatedly, the timer scheduling component uses a distributed lock in shared storage to ensure that only one instance proceeds with scheduling at any given time. The holding time of the distributed lock is exemplarily set to 5 seconds, after which it is automatically released to prevent scheduling from stalling due to lock holder failure.
[0085] The timer scheduling component maintains two independent scheduling cursors, each recording the processing progress of a different scheduling mode. The first scheduling cursor (i.e., the normal scheduling cursor, specifically `lastTickTime` in this embodiment) records the time elapsed since the most recent normal scheduling session. Each time the first scheduling cursor completes, it is updated to reflect the end time of the latest time slot processed in this tick. The second scheduling cursor (i.e., the historical frame tracking cursor, specifically `lastMisfireTime` in this embodiment) records the time elapsed since the historical expired time slots were processed. Frame tracking refers to compensatory scanning and execution of historical expired time slots that were not processed in time due to service restarts, network interruptions, or scheduling delays.
[0086] In this embodiment, the first scheduling cursor first processes the expired timers in the current time slot, and then determines whether there are any unprocessed historical expired slots based on the second scheduling cursor and performs frame tracking. When the asynchronous task queue is full or processing fails, the cursor does not cross the earliest failed time slot to avoid tasks being skipped incorrectly.
[0087] For example, when the historical frame tracking progress recorded by the second scheduling cursor is 10:00:00 on January 10, 2026, and there are currently 5 unprocessed historical expired time slots from 10:00:01 to 10:00:05 on January 10, 2026, the frame tracking logic scans and processes slot by slot starting from the position pointed to by the second scheduling cursor. After processing each time slot, the second scheduling cursor is pushed forward one step. If the asynchronous task queue is full when processing the time slot corresponding to 10:00:03 on January 10, 2026, the second scheduling cursor stays at 10:00:03, and processing continues from that position in the next scheduling.
[0088] It should be noted that after the time change message completes the time replacement within the service process where the timer scheduling component resides, it triggers its registered time change callback. The callback function then loops through the time-limited context, attempting to acquire the distributed lock of the timer scheduling component.
[0089] For example, the callback timeout is set to 10 seconds, and the retry interval is 200 milliseconds, meaning a maximum of 50 attempts to acquire the lock. During the waiting period, if the first scheduling cursor is executing, the callback function waits for it to release the lock before acquiring it again. After successfully acquiring the lock, the callback function reads the replaced current time and corrects the scheduling cursor in shared storage. If the lock cannot be acquired within the timeout period, the callback function records an error log of the lock acquisition failure and ends the current correction. The execution result of the time change callback of the timer scheduling component does not block the execution of other callbacks.
[0090] In this embodiment, the correction process includes the following operation: adjusting the first scheduling cursor to the replaced time so that the next Tick continues to advance from the new timeline.
[0091] For example, when the original lastTickTime is January 10, 2026, 10:00:00, and the replaced time is January 15, 2026, 10:00:00, the lastTickTime is set to January 15, 2026, 10:00:00, and the next tick will begin scanning the time slot from January 15, 2026, 10:00:01. For the time slots between the first scheduling cursor and the replaced time (i.e., all time slots from January 10, 2026, 10:00:01 to January 15, 2026, 09:59:59), since the timers in these time slots have expired during the time progression, the frame tracking logic will perform compensatory scanning and execution on them in subsequent ticks using the second scheduling cursor.
[0092] Simultaneously, it is determined whether the second scheduling cursor has exceeded the replacement time. If the second scheduling cursor has exceeded the replacement time, it means that the processing progress of historical frame tracking has exceeded the current position of the new timeline. Continuing to track frames along the old timeline will scan into future time slots, causing timers that have not yet expired to be triggered prematurely. In this case, the second scheduling cursor is rolled back to the replacement time to avoid tracking frames along the old timeline.
[0093] For example, when the original lastMisfireTime is January 11, 2026, 08:00:00, and the replaced time is January 15, 2026, 10:00:00, since lastMisfireTime (January 11, 08:00:00) does not exceed the replaced time (January 15, 10:00:00), the original value is retained, and the frame tracking logic continues to track frames from January 11, 08:00:00 towards January 15, 10:00:00. When the original lastMisfireTime is January 20, 2026, 08:00:00, because lastMisfireTime (January 20, 08:00:00) exceeds the replacement time (January 15, 10:00:00), lastMisfireTime will be rolled back to January 15, 2026, 10:00:00 to avoid the frame tracking logic scanning timers that have not yet expired in the time slots after January 15, 10:00:00.
[0094] Furthermore, for periodic timers with repetitive execution attributes, the processing method after cursor correction is the same as for non-repetitive timers. After each trigger, the periodic timer re-determines the next execution time based on the execution interval and updates the time slot index. After the cursor advances, when the frame tracking logic scans an expired periodic timer, it triggers its callback message and updates its next execution time to a future time point on the replaced timeline based on the execution interval.
[0095] For example, a periodic timer with an execution interval of 3600 seconds (1 hour) originally had its next execution time set for January 10, 2026 at 11:00:00. After the time advances to January 15, 2026 at 10:00:00, the frame tracking logic triggers the timer's expiration callback and updates its next execution time to January 15, 2026 at 11:00:00. Subsequently, the first scheduling cursor will continue to trigger the timer when it reaches that time point.
[0096] When the target time is earlier than the current real time, i.e., a scenario where time rolls back to the past, the cursor correction also executes the same logic. The first scheduling cursor is set to the replacement time. Since this time is earlier than the previous TickTime, the scheduler starts scanning from the replacement time in the next tick. The conditional rollback logic for the second scheduling cursor also applies, i.e., rollback occurs if lastMisfireTime exceeds the replacement time.
[0097] For example, when the original `lastTickTime` is January 15, 2026, at 10:00:00, and the target time is January 5, 2026, at 10:00:00, `lastTickTime` is set to January 5, 2026, at 10:00:00. At this time, timers in the time slots between January 5, 2026, at 10:00:00 and January 15, 2026, at 10:00:00, may have already been executed. When the scheduler scans these time slots, it determines whether repeated triggering is necessary based on the execution status recorded in the timer body. Non-repeating timers marked as executed are skipped, while periodic timers are rescheduled according to the execution interval.
[0098] The complete execution flow of the cursor correction process is as follows: acquire the distributed lock, read the current replacement time and lastTickTime and lastMisfireTime from the shared storage, set lastTickTime to the replacement time, determine if lastMisfireTime is greater than the replacement time, if it is, set lastMisfireTime to the replacement time, write the corrected cursor value back to the shared storage, and release the distributed lock. All read and write operations are completed within the same lock protection period, ensuring the atomicity of cursor correction.
[0099] The above read and write operations are performed under lock protection to avoid data inconsistency caused by time correction and concurrent ticks modifying the cursor simultaneously. The distributed lock is acquired using a combination of non-blocking attempt acquisition and short-term waiting. Each time the callback function attempts to acquire the lock, it sends a lock acquisition request with an expiration time to the shared storage. If the lock is not currently held, the acquisition succeeds and the lock holder identifier is set to the current instance; if the lock is already held by another instance, the acquisition fails.
[0100] If the acquisition fails, the callback function waits 200 milliseconds before attempting again. The lock holder identifier uses an instance-unique identifier plus a random token format. When releasing the lock, the holder identifier must be verified to ensure a match before release is allowed, preventing the accidental release of locks held by other instances.
[0101] For example, when the first scheduling cursor is executing and holding a distributed lock, the cursor correction callback function acquires the lock and performs correction after waiting for the first scheduling cursor to complete and release the lock. The waiting time is typically in the range of milliseconds to seconds, not exceeding the execution time of a single execution of the first scheduling cursor.
[0102] The mutual exclusion between the cursor correction and the first scheduled cursor ensures the following consistency: During cursor correction execution, the first scheduled cursor will not read the cursor value in the intermediate correction state, and there will be no inconsistent window where the first scheduled cursor has advanced but the second scheduled cursor has not yet made a judgment. During the execution of the first scheduled cursor, cursor correction will not concurrently modify the cursor value, and there will be no race condition where Tick is correcting the cursor that has already advanced to a new position based on the old cursor scanning time slot.
[0103] After the correction is completed, the distributed lock is released, and the first scheduling cursor continues to scan the time slot, read the timer body, and send the scheduled callback message according to the corrected cursor in the next scheduling cycle. The timer scheduling component maintains an execution status flag for each timer, which includes three states: pending execution, delivered, and completed.
[0104] Among them, the pending state indicates that the timer has not yet expired or has expired but has not yet been processed by the scheduler; the delivered state indicates that the scheduler has sent the expired message to the asynchronous task queue but has not yet received the execution confirmation; and the completed state indicates that the expired message has been successfully consumed by the target service.
[0105] When the cursor advances and scans for frames, it skips non-repeating timers that are already completed. When it scans for timers in the pending execution state, it triggers their expiration callback and updates their status to "delivered." This state management mechanism prevents completed timers from being triggered repeatedly after a time jump.
[0106] The frame tracking logic sets a single frame tracking depth limit to control the resource consumption of the scheduler by the frame tracking operation. For example, the maximum number of time slots processed in a single tick is set to 3600 (corresponding to a 1-hour time span). When this number is exceeded, frame tracking is paused, and the remaining historical expired slots are reserved for subsequent scheduling. The frame tracking depth limit prevents large time jumps from causing too many historical time slots to be processed in a single scheduling operation, affecting the timely scheduling of the current time slot. The parameter value of the frame tracking depth limit is set according to actual needs, and is exemplary in the range of 1000 to 7200; in this embodiment, it is set to 3600.
[0107] The scheduling cursor and timer body data are persistently stored in shared storage as key-value pairs. The storage key for the first scheduling cursor can be "timer:cursor:lastTickTime", and the storage key for the second scheduling cursor can be "timer:cursor:lastMisfireTime". The storage key for the time slot index uses the timestamp corresponding to the time slot as a suffix, for example, "timer:slot:1736928000" represents the time slot corresponding to UTC time January 15, 2025, 08:00:00. The value of each time slot is an ordered set of all timer identifiers within that slot. This storage structure allows the scheduler to directly locate the target time slot using the timestamp, and cursor correction operations can also be completed by directly updating the key value without traversing the entire dataset.
[0108] The correction applies to timers and their scheduling states that already exist in shared storage, rather than creating new timers. After the timeline switches from real time to test time, or reverts from test time to real time, existing unfinished timers can still be realigned and continue execution via cursor.
[0109] When restoring the real time, after each service instance receives a recovery message carrying an empty target time, the message processor of each service process detects that the target time is empty and enters the recovery process. In the recovery process, the message processor undoes the replacement of the time acquisition function within the process, restores the time acquisition function to the original implementation of the standard library, and clears the time offset, resetting the offset value to zero.
[0110] After the recovery operation is completed, the time replacement processor iterates through the time change callback list again and executes each callback function in sequence. Upon receiving the recovery notification, the time change callback of the timer scheduling component performs the same cursor correction process using the recovered real current time.
[0111] For example, if the previous lastTickTime was 10:05:00 on January 15, 2026 (test timeline), and the current real time after recovery is 10:05:00 on January 10, 2026, then lastTickTime will be corrected to 10:05:00 on January 10, 2026. The same over-limit judgment and conditional rollback logic will also be performed on lastMisfireTime.
[0112] The recovery process and setup process use the same message topic and broadcast link. Each service instance distinguishes the operation type by the null / non-null value of the target time field, without requiring additional control signaling. After recovery, each service process uses the real system time, and the timer scheduler continues to scan and execute along the real timeline to avoid inconsistencies where the business time has been restored but the timer is still stuck on the test timeline.
[0113] This application also provides a container time isolation control system based on service-level switches and namespaces. For example... Figure 3 As shown, the system includes the following modules: The time message publishing module is used to publish time change messages carrying the target time to the message queue.
[0114] The time message publishing module is deployed in the time control service. It receives time modification requests from clients, performs format parsing and business verification on the target time, and constructs a time change message and publishes it to the specified topic of the message queue after the verification is passed.
[0115] The time message publishing module internally comprises a request receiving subunit, a parameter validation subunit, and a message construction subunit. The request receiving subunit listens to the client's debugging interface and parses the request parameters. The parameter validation subunit verifies the format and validity of the target time. The message construction subunit encapsulates the validated target time into a standard time change message and calls the message queue's publishing interface to complete the message transmission. The time message publishing module determines the message distribution scope through service-level switches and namespace configuration, distributing the time change message only to service processes that have enabled the service-level switch and configured the corresponding namespace.
[0116] The time replacement module, deployed within the service process of each target container, determines the time offset based on the target time and the current real time, and corrects the return value of the time acquisition function to the time obtained by adding the time offset to the underlying real time. During the service process startup phase, the time replacement module creates a message queue broadcast consumer and registers a message handler.
[0117] The time replacement module internally includes a message consumption subunit, an offset management subunit, and a function replacement subunit. The message consumption subunit is responsible for receiving time change messages from the message queue and extracting the target time field. The offset management subunit is responsible for calling the underlying real time function to obtain the current real time and determine the time offset. The function replacement subunit is responsible for performing runtime replacement on the in-process standard time acquisition function, so that the replaced time acquisition function returns a time value with the offset added.
[0118] The change callback module is used to trigger registered time change callbacks after the time acquisition function is replaced. This module maintains a list of time change callbacks, and each business component registers a callback function with the module during the initialization phase.
[0119] The change callback module internally comprises a callback registration subunit and a callback execution subunit. The callback registration subunit provides registration and deregistration interfaces to maintain the consistency of the callback list. The callback execution subunit, after time replacement, iterates through the callback list in registration order and executes each callback function sequentially. The callback execution subunit employs a fault-tolerance and isolation strategy, ensuring that the failure of a single callback function does not prevent the continuation of other callbacks. After time replacement, the change callback module iterates through the callback list and executes each callback function sequentially, notifying the time change event to components such as the timer scheduling component that need to correct the timeline state.
[0120] The cursor correction module is used to respond to the time change callback, adjust the first scheduling cursor to the replacement time under mutual exclusion protection, and roll back the second scheduling cursor to the replacement time when the second scheduling cursor exceeds the replacement time. The cursor correction module is registered in the change callback module as a callback function of the timer scheduling component.
[0121] The cursor correction module internally includes a lock acquisition subunit, a cursor reading subunit, and a cursor writing subunit. Upon receiving a time change callback notification, the lock acquisition subunit repeatedly attempts to acquire the distributed lock of the timer scheduling component within a limited timeout period. After successfully acquiring the lock, the cursor reading subunit reads the current values of the first and second scheduling cursors from shared storage. The cursor writing subunit performs cursor adjustment and conditional rollback logic based on the replaced time and writes the corrected cursor value back to shared storage. After correction, the distributed lock is released, allowing existing timers to continue execution along the new timeline.
[0122] In one deployment implementation, the time message publishing module and the time control service are deployed in the same service instance. The time replacement module and the change callback module are embedded in the business service processes within each target container as components of a general application framework. The cursor correction module is embedded in the service process of the timer management service as a callback function. The general application framework automatically initializes the time replacement module and the change callback module during the service process startup phase, enabling the service process to modify time without requiring business developers to write additional code.
[0123] Each module in the system can be implemented by a processor executing computer programs stored in memory. The time message publishing module, time replacement module, change callback module, and cursor correction module interact with each other via message queues and shared storage. The output (time change message) of the time message publishing module is transmitted to the time replacement module through the message queue. After the time replacement module completes the replacement, it triggers the callback execution of the change callback module, which then notifies the cursor correction module to perform cursor correction. The functional division of each module corresponds one-to-one with the steps in the above method embodiment.
[0124] Example 2: In Example 1, the replaced time acquisition function reads the underlying real time each time it is called and adds the time offset to that reading. When the physical node carrying the service process performs network time protocol synchronization or virtual machine hot migration, the underlying real time may jump backward. At this time, the result of the added offset will also roll back, and the replaced time will no longer advance monotonically. The replaced time read by the timer scheduling component may be less than the first scheduling cursor that has advanced in the previous scheduling cycle, resulting in a secondary misalignment between the scheduling state and the service time.
[0125] To address this, the time replacement processor in this embodiment records two reference anchor points at the same moment the time offset is determined. The replaced time anchor point is the target time. The monotonic clock anchor point is the reading from the underlying monotonic time interface at that moment. The underlying monotonic time interface is a time reading interface that monotonically increases with real time and is not affected by system time adjustments. For example, in Go, a runtime-provided monotonic clock reading interface is used; in C, a CLOCK_MONOTONIC clock source is used; and in Java, System.nanoTime is used.
[0126] When the replaced time acquisition function is called, it reads the current reading of the underlying monotonic time interface, adds the difference between the current reading and the monotonic clock anchor point to the replaced time anchor point, and uses the addition result as the return value. The return value advances with the real time, and its advancement process is decoupled from the adjustment of the underlying real time.
[0127] For example, the target time in the process is set to 10:00:00 on January 15, 2026, and the read underlying real time is 10:00:00 on January 10, 2026. The time offset is 432,000 seconds. The monotonic clock reading at this offset is determined to be 1,000,000 seconds. After replacement, the time anchor point is set to 10:00:00 on January 15, 2026, and the monotonic clock anchor point is set to 1,000,000 seconds. After advancing the real time by 30 seconds, the monotonic clock reading is 10,000,30 seconds, and the replaced time acquisition function returns 10:00:30 on January 15, 2026.
[0128] The time replacement processor performs a baseline recalibration once per recalibration cycle. During the recalibration process, it reads the underlying real time and the underlying monotonic time interface, and determines the wall clock deviation as follows: The wall clock estimated time is obtained by adding the time offset to the currently read underlying real time. The monotonic clock difference is obtained by adding the monotonic clock difference to the replaced time anchor point, where the monotonic clock difference is the difference between the currently read monotonic clock reading and the monotonic clock anchor point. The difference between the wall clock estimated time and the monotonic clock estimated time is taken as the wall clock deviation.
[0129] It should be noted that the recalibration is handled in three ways depending on the value of the wall clock deviation: When the wall clock deviation exceeds a positive threshold, it is determined that the underlying real time has jumped forward. The replaced time anchor point is then updated to the wall clock's calculated time, and the monotonic clock anchor point is updated to the monotonic clock reading of this reading.
[0130] When the wall clock deviation is less than the negative threshold, it is determined that the underlying real time has jumped backward. The replacement time anchor point and the monotonic clock anchor point remain unchanged, and the absolute value of the wall clock deviation is recorded as the wall clock back misalignment amount.
[0131] When the absolute value of the wall clock deviation is less than the positive threshold, the two anchor points remain unchanged and no anchor point update is performed.
[0132] The absolute values of the positive threshold and the negative threshold are the same, and are exemplarily set to 1 second. The value is determined by the business's constraint on timestamp continuity. If the deviation is less than this value, updating the anchor point will cause non-monotonic jitter in the replaced time; if the deviation is greater than this value, keeping the anchor point unchanged will cause a long-term separation between the replaced time and the underlying real time. The recalibration period is exemplarily set to 300 seconds, based on the fact that the cumulative relative drift between the monotonic clock and the underlying real time within this duration is less than the positive threshold, thus eliminating the need for more frequent calibration.
[0133] For example, after the setup process is completed, recalibration is triggered at the 300th second. The monotonic clock reading this time is 1000300 seconds, and the monotonic calculated time is 10:05:00 on January 15, 2026. If the physical node performs a backward time adjustment within these 300 seconds, the underlying real time read this time is 10:04:58 on January 10, 2026, and the wall clock calculated time is 10:04:58 on January 15, 2026, with a wall clock deviation of -2 seconds. At this time, keeping the two anchor points unchanged, the wall clock misalignment is recorded as 2 seconds, and the time after replacement remains 10:05:00 on January 15, 2026, without jumping backward. If the physical node performs a forward time synchronization within the 300 seconds, the underlying real time read this time is 10:05:02 on January 10, 2026, the calculated time of the wall clock is 10:05:02 on January 15, 2026, and the wall clock deviation is positive 2 seconds. At this time, the replaced time anchor point is updated to 10:05:02 on January 15, 2026, and the monotonic clock anchor point is updated to 1000300 seconds.
[0134] After the anchor point update is completed, the time replacement processor triggers a baseline recalibration notification to the callback list. The baseline recalibration notification and the time change callback use the same registration mechanism and the same fault tolerance and isolation mechanism. The timer scheduling component responds to the baseline recalibration notification by reviewing the first and second scheduling cursors with the updated replacement time, using the same cursor advance and conditional rollback logic under mutual exclusion protection. Since backward jumps do not trigger anchor point updates, the replacement time does not roll back, and the first scheduling cursor does not regress. Deviations caused by forward jumps are gradually absorbed by subsequent normal scheduling along the new timeline.
[0135] The wall clock rollback misalignment amount is included in the time modification status information of the service process and output externally through the time status query endpoint. In one embodiment, the query endpoint outputs the value when the wall clock rollback misalignment amount is 2 seconds, so that testers can judge the degree of deviation between the replaced time and the underlying real time.
[0136] Optionally, the reading of the underlying monotonic time interface can also be obtained by summing the wall clock reading at the start of the service process and the cumulative runtime of the process, that is, maintaining a time measurement quantity that advances according to the cumulative runtime within the process. Optionally, for operating environments that do not provide a monotonic clock reading interface, the underlying real time read this time can be compared with the underlying real time read last time within the time acquisition function after replacement. If the current reading is less than the previous reading, the return value of the previous reading is used, which also ensures that the time after replacement does not go backward. Optionally, the recalibration period can also be dynamically adjusted according to the measured drift rate of the monotonic clock and the underlying real time. When the drift rate is large, the recalibration period is shortened.
[0137] This embodiment uses a monotonic clock differential to drive the advancement of the replaced time, so the monotonicity of the replaced time no longer depends on the stability of the underlying real time. Changes in the underlying real time caused by host time synchronization and virtual machine hot migration are no longer propagated to the replaced time. The scheduling cursor does not regress due to time base backtracking, and periodic base recalibration ensures that the replaced time remains aligned with the underlying real time on a long-term timescale.
[0138] Those skilled in the art will understand that not every method step in the above embodiments is essential, and certain steps may be omitted or their execution order adjusted in specific application scenarios. The scope of protection of this application is determined by the claims.
[0139] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit described above can be implemented in hardware.
[0140] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any changes or substitutions within the technical scope disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.
Claims
1. A container time isolation control method based on service-level switches and namespaces, characterized in that, include: A time change message carrying the target time is published to a message queue, and the time change message is received by the service processes in multiple target containers respectively. Each service process determines the time offset based on the target time and the current real time, and corrects the return value of the time acquisition function to the time obtained by superimposing the time offset on the underlying real time, so that the service process obtains the replacement time as the real time progresses; After the time acquisition function is replaced, the time change callback registered in the service process is triggered; The timer scheduling component responds to the time change callback by performing cursor correction, which includes: reading the replaced time under mutual exclusion protection; adjusting the first scheduling cursor to the replaced time; and when the second scheduling cursor exceeds the replaced time, rolling back the second scheduling cursor to the replaced time, so that the existing timer continues to execute along the new time axis.
2. The method according to claim 1, characterized in that, Also includes: Each service process reads the configuration values of service-level switches and the namespace configuration bound to it during the startup phase; With the service-level switch enabled and the namespace configured, a broadcast consumer for the message queue is created and subscribed to the message topic corresponding to the namespace. The time change message is broadcast to the service processes that subscribe to the message topic through the message queue. Service processes that have not enabled the service-level switch or have not configured the namespace do not receive the time change message. Each service process performs an idempotency check based on the message identifier carried in the time change message and discards duplicate time change messages.
3. The method according to claim 1 or 2, characterized in that, The time change message includes: Receive a time modification request initiated by a client, the time modification request carrying the target time; The target time is parsed and validated for its format, and after the validation is passed, a time change message carrying the target time is constructed. The time change message is published to the message topic bound to the namespace in the message queue; After receiving a successful publication confirmation response from the message queue, the system returns the operation result to the client; if publication fails or the confirmation response is not received within a preset timeout period, a retry is performed, and an operation failure response is returned after the number of retries is exhausted.
4. The method according to claim 1, characterized in that, Determining the time offset and correcting the return value of the time acquisition function includes: The current real time is read using the underlying time function that has not been replaced; The time offset is determined based on the target time and the current real time, and the time offset is written into the memory space of the service process through atomic operations; The return value of the time acquisition function is corrected by the time offset so that the replaced return value advances synchronously with the current real time.
5. The method according to claim 1, characterized in that, The time change callback is triggered by: Arrange the registered time change callbacks in the service process into a callback list according to the registration order, and iterate through the callback list; Each time change callback in the callback list is executed synchronously in sequence, and the replaced time is passed to each time change callback. If any time change callback fails or times out, log an error and continue executing the remaining time change callbacks in the callback list.
6. The method according to claim 1, characterized in that, Also includes: The timer scheduling component persistently stores the timer body and time slot index in shared storage; The timer scheduling component reads the time slots that should be processed from the shared storage at a preset period and sends expiration messages to the timers that are expiring in the time slots. During the scheduling process, the timer scheduling component acquires a distributed lock through the mutual exclusion mechanism in the shared storage and releases the distributed lock after the current scheduling is completed, so as to ensure that the scheduling is carried out by a single instance.
7. The method according to claim 6, characterized in that, The timer scheduling component performs scheduling including: In normal scheduling, the first scheduling cursor is updated to the end time of the latest time slot processed in this scheduling. The unprocessed historical expiration time slots are determined according to the second scheduling cursor, and the historical expiration time slots are scanned and executed slot by slot starting from the position indicated by the second scheduling cursor. After processing each historical expiration time slot, the second scheduling cursor is pushed forward one step, and if the current scheduling fails, the second scheduling cursor is stopped at the earliest failed time slot. When the number of historical expired time slots processed in this scheduling reaches the preset depth limit, the scanning is paused, and the remaining historical expired time slots are retained for processing in the next scheduling.
8. The method according to claim 1, characterized in that, Also includes: Each service process receives a recovery message broadcast by the message queue, the recovery message carrying an empty target time; Remove the replacement of the time acquisition function within the process and clear the time offset, so that the service process can resume using the real system time; The time change callback registered in the service process is triggered again, and the timer scheduling component responds to the time change callback to correct the first scheduling cursor and the second scheduling cursor with the restored real current time.
9. A container time isolation control system based on service-level switches and namespaces, characterized in that, include: The time message publishing module is used to publish a time change message carrying the target time to the message queue. The time change message is received by the service processes in multiple target containers respectively. The time replacement module is deployed in the service process within each target container. It is used to determine the time offset based on the target time and the current real time, and to correct the return value of the time acquisition function to the time obtained by adding the time offset to the underlying real time. The change callback module is used to trigger the registered time change callback after the time acquisition function is replaced; The cursor correction module is used to perform cursor correction in response to the time change callback. The cursor correction includes: adjusting the first scheduling cursor to the replacement time under mutual exclusion protection, and rolling back the second scheduling cursor to the replacement time when the second scheduling cursor exceeds the replacement time.
10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, implements the method of any one of claims 1 to 8.
