A timing task weak clock drift adaptive calibration scheduling method and system

CN122614520APending Publication Date: 2026-08-21ZETIAN ZHIHANG ELECTRONIC TECHNOLOGY (SICHUAN) CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610939850.0
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-06-26
Publication Date
2026-08-21

AI Technical Summary

Technical Problem

[0008]针对现有技术中网络对时在断网状态下失效、硬件时钟增强成本较高、负载波动未被纳入漂移补偿以及集中修正容易引发任务调度雪崩的不足,本申请提供了一种定时任务弱时钟漂移自适应校准调度方法及系统

Benefits of technology

[0016] Compared with existing technologies, this application has at least the following advantages: First, this application forms the drift judgment basis based on local system ticks, scheduling ticks, and processor load intensity, without relying on external network time servers or requiring the addition of high-precision RTCs or temperature-compensated crystal oscillators, thus enabling it to be adapted to low-cost embedded devices. Second, this application incorporates load changes and scheduling delays into the drift prediction process, allowing offset changes in high-load phases to enter compensation calculations more quickly and making compensation outputs in low-load phases smoother. Third, this application breaks down the predicted drift amount into multiple fine-tuning segments and limits the single-cycle correction amplitude, which can avoid sudden changes in task triggering caused by a large one-time correction. Fourth, this application rearranges the task queue based on the correction trigger timestamp and performs anti-avalanche scheduling for conflicting tasks, which can reduce the instantaneous impact on the scheduler caused by multiple tasks triggering simultaneously. Fifth, this application uses calibration performance indicators to feedback and adjust the sampling period, the number of fine-tuning segments, and load coupling parameters, enabling the calibration strategy to continuously adapt to the device's operating status.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122614520A_ABST
    Figure CN122614520A_ABST
Patent Text Reader

Abstract

The application discloses a timing task weak clock drift adaptive calibration scheduling method and system, and relates to the technical field of embedded system scheduling. The method obtains clock characteristic data formed by system tick count deviation, scheduling beat deviation and processor load intensity, and determines a global clock drift reference value; in combination with load change and scheduling delay, a drift prediction result is generated, the predicted drift amount is split into multiple fine adjustment sub-sections to correct a task trigger timestamp, and anti-avalanche scheduling is performed when a trigger conflict occurs; and then, a calibration efficiency index is fed back to adjust parameters. The scheme can realize pure software closed-loop compensation of timing task drift under the condition of no network time setting and no high-precision hardware clock.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of embedded system scheduling technology, and in particular to a method and system for adaptive calibration scheduling of weak clock drift for timed tasks under conditions of weak precision local clock, offline operation, and low-resource hardware. Background Technology

[0002] In industrial control, IoT terminals, smart meters, vehicle edge controllers, and field monitoring equipment, timed task scheduling typically handles functions such as periodic data acquisition, control loop execution, and communication protocol heartbeats. It can also perform sensor polling, watchdog maintenance, and status log recording. Whether these services trigger at the expected time directly affects the stability of the control cycle, the interval of data sampling, and the real-time performance of the communication link. For embedded devices using low-end mainframes, the local clock is often provided by a common quartz crystal, on-chip RC oscillator, or low-cost counter. Frequency stability, temperature drift characteristics, and long-term operational stability are all limited by hardware conditions, thus causing a continuous deviation between the theoretical and actual trigger times of timed tasks.

[0003] Existing clock calibration and scheduled task synchronization solutions mainly include network time synchronization solutions and hardware clock enhancement solutions. Network time synchronization solutions typically rely on NTP or PTP servers to obtain external standard time through periodic interactions and correct the local system time accordingly. This solution can obtain a good time reference in scenarios with stable network connections, but in industrial sites, mobile terminals, field equipment, closed intranets, and secure isolation devices, network connections may be unavailable for extended periods or be intermittent. Once the network is interrupted, the external time reference cannot be continuously input, and local scheduled task drift will continue to accumulate over time.

[0004] Hardware clock enhancement solutions typically improve timing accuracy through RTC chips, temperature-compensated crystal oscillators, or more stable oscillators. This approach reduces clock drift at the hardware level but increases material costs, power budgets, and board area, and may also introduce additional issues such as backup battery maintenance, temperature-compensated calibration, and hardware failure detection. For embedded devices targeting low cost, miniaturization, and low power consumption, relying solely on hardware upgrades is not always feasible.

[0005] In addition to the aforementioned external time and hardware stability issues, embedded timed tasks are also affected by system load fluctuations. The scheduler latency, task switching interval, and context switching frequency can all vary under conditions of idleness, communication bursts, intensive control computation, or frequent interruptions. If the calibration algorithm only considers the local clock frequency deviation without considering the coupling relationship between processor load and scheduling latency, the actual triggering deviation during high-load phases may not be reflected in the compensation strategy in a timely manner, while overcompensation or jitter may occur during low-load phases.

[0006] Existing solutions often involve a one-time correction of the trigger time. This approach directly changes the task trigger time after detecting a large drift, which may cause multiple periodic tasks to trigger at close intervals, resulting in a sudden increase in scheduler load, increased task response latency, control loop jitter, and communication queue congestion. For multiple task queues with different periods and priorities, centralized correction may also disrupt the original scheduling order, causing high-priority control tasks and low-priority maintenance tasks to compete for each other's time.

[0007] Therefore, a scheduling calibration mechanism is needed that does not rely on external networks, does not require additional high-precision hardware clocks, and can adaptively compensate for weak clock drift using local operating data. This mechanism should also be able to sense load fluctuations, avoid scheduling avalanches caused by concentrated corrections, and continuously evaluate the calibration effect and adjust parameters during long-term offline operation. Summary of the Invention

[0008] To address the shortcomings of existing technologies, such as network time synchronization failure during network outages, high hardware clock enhancement costs, lack of load fluctuation inclusion in drift compensation, and the potential for centralized correction to trigger task scheduling avalanche, this application provides a method and system for adaptive calibration scheduling with weak clock drift for timed tasks. This method collects clock characteristic data from system tick count deviation, scheduling tick deviation, and processor load intensity. It determines a global clock drift baseline value based on the theoretical and actual trigger times of the timed tasks. Then, it combines load change status and scheduling delay status to form a load-coupled drift prediction result. Gradual compensation is achieved through segmented fine-tuning and queue rearrangement. Finally, the calibration performance index is used to adjust the sampling period, the number of fine-tuning segments, and the load coupling parameters.

[0009] The adaptive calibration scheduling method for weak clock drift of scheduled tasks provided in this application includes: acquiring system tick count deviation, scheduling tick deviation, and processor load intensity within a preset sampling period to form clock characteristic data, and determining a global clock drift reference value based on the theoretical and actual trigger times of the scheduled tasks; determining the clock drift rate based on the time series of the clock characteristic data, and forming a load coupling drift prediction result by combining the load change state and scheduling delay state; dividing the predicted drift amount corresponding to the load coupling drift prediction result into multiple fine-tuning segments, and correcting the theoretical trigger time of the scheduled tasks according to the fine-tuning segments to obtain a corrected trigger timestamp, wherein the correction magnitude within a single scheduling period is constrained by a preset upper limit ratio; rearranging the scheduled task queue according to the corrected trigger timestamp, and performing anti-avalanche scheduling based on task priority and minimum safety interval when the trigger times of multiple scheduled tasks fall into the same conflict time window; forming a calibration performance index based on the task trigger offset dispersion, scheduling delay increment, and processing resource overhead within the calibration period, and adjusting the sampling period, the number of fine-tuning segments, and the load coupling parameters based on the calibration performance index.

[0010] Optionally, the formation of the clock characteristic data includes obtaining the deviation of the system tick cumulative value from the theoretical tick cumulative value, obtaining the deviation of the actual tick between adjacent trigger events of the scheduler from the theoretical tick, and determining the processor load intensity based on the processor active cycle, idle cycle, run queue length, and context switching frequency. By combining the above data, the local counter frequency deviation, scheduler operation deviation, and load disturbance degree can be characterized simultaneously.

[0011] Optionally, the global clock drift reference value is formed by weighting the single-task offsets of multiple timing tasks, and the weighting result is subjected to sliding window filtering and transient offset reduction processing. This reduces the impact of occasional blocking, interruption jitter, or abnormal preemption of a single task on the global drift determination.

[0012] Optionally, the load coupling drift prediction result is smoothly updated based on the continuously sampled global clock drift reference value, and the prediction sensitivity is increased when the processor load intensity increases or the load change amplitude increases, and decreased when the processor load intensity decreases and the load change amplitude decreases. This allows the compensation strategy to respond promptly during high load phases and remain stable during low load phases.

[0013] Optionally, the fine-tuning segments are allocated in a linearly decreasing or exponentially decaying manner, and the trigger time correction amount generated by each fine-tuning segment in the current scheduling cycle does not exceed the preset proportion upper limit of the current scheduling cycle. This process can distribute the correction amount, which might otherwise occur in a concentrated manner, across multiple scheduling cycles, reducing the risk of sudden changes in task trigger time.

[0014] Optionally, the avalanche prevention scheduling includes conflict time window detection, conflict task set determination, task priority sorting, and minimum safety interval insertion. Through the above processing, high-priority tasks can maintain a trigger position closer to their corrected trigger timestamp, while low-priority tasks are appropriately shifted back according to priority differences, thereby dispersing the scheduler's instantaneous load peak.

[0015] This application also provides a timed task weak clock drift adaptive calibration scheduling system, including a drift sampling module, a drift prediction module, a fine-tuning calculation module, a scheduling rearrangement module, and a performance evaluation module. The drift sampling module is used to generate clock characteristic data and a global clock drift reference value; the drift prediction module is used to generate load-coupled drift prediction results; the fine-tuning calculation module is used to calculate fine-tuning segments and generate correction trigger timestamps, and constrain the correction magnitude within a single scheduling cycle; the scheduling rearrangement module is used to rearrange the timed task queue and perform avalanche prevention scheduling; and the performance evaluation module is used to adjust calibration parameters based on calibration performance feedback.

[0016] Compared with existing technologies, this application has at least the following advantages: First, this application forms the drift judgment basis based on local system ticks, scheduling ticks, and processor load intensity, without relying on external network time servers or requiring the addition of high-precision RTCs or temperature-compensated crystal oscillators, thus enabling it to be adapted to low-cost embedded devices. Second, this application incorporates load changes and scheduling delays into the drift prediction process, allowing offset changes in high-load phases to enter compensation calculations more quickly and making compensation outputs in low-load phases smoother. Third, this application breaks down the predicted drift amount into multiple fine-tuning segments and limits the single-cycle correction amplitude, which can avoid sudden changes in task triggering caused by a large one-time correction. Fourth, this application rearranges the task queue based on the correction trigger timestamp and performs anti-avalanche scheduling for conflicting tasks, which can reduce the instantaneous impact on the scheduler caused by multiple tasks triggering simultaneously. Fifth, this application uses calibration performance indicators to feedback and adjust the sampling period, the number of fine-tuning segments, and load coupling parameters, enabling the calibration strategy to continuously adapt to the device's operating status. Attached Figure Description

[0017] Figure 1 A flowchart of the weak clock drift adaptive calibration scheduling method provided in the embodiments of this application.

[0018] Figure 2 A schematic diagram of the multidimensional clock drift sampling and benchmark modeling architecture provided in the embodiments of this application.

[0019] Figure 3 The flowchart shows the calculation process of the load coupling drift prediction model provided in the embodiments of this application.

[0020] Figure 4 The logic diagram for segmented fine-tuning quantity allocation and trigger timing correction provided in the embodiments of this application is shown.

[0021] Figure 5 The timing diagram for task scheduling sequence rearrangement and avalanche prevention control provided in the embodiments of this application.

[0022] Figure 6 This is a closed-loop block diagram for calibration performance evaluation and parameter iteration provided in the embodiments of this application.

[0023] Figure 7 This is a diagram illustrating the system module interaction and data flow architecture provided in the embodiments of this application.

[0024] Figure 8 A comparison curve of the timed task offset in an industrial PLC scenario provided in the embodiments of this application. Detailed Implementation

[0025] 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.

[0026] 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.

[0027] The embodiments of this application are described below with reference to the accompanying drawings. It should be understood that the embodiments described herein are used to explain the technical solutions of this application and are not intended to limit the scope of protection of this application. Where there is no conflict, the technical features in the following embodiments can be combined with each other, and the parameter ranges, interface names, and platform names can be replaced according to the actual embedded system.

[0028] like Figure 1As shown, the method in this application calibrates around the trigger time of the scheduled task, rather than simply rewriting the system wall time. This method takes local runtime data as input. It forms a closed loop through clock characteristic data sampling, load-coupled drift prediction, and piecewise fine-tuning compensation, combined with task queue rearrangement to prevent avalanche and calibration performance feedback. This application extracts state variables reflecting weak clock drift from system tick counts, scheduler ticks, and processor load without adding an external time server or high-precision hardware clock. These state variables are then applied to the generation process of the scheduled task trigger timestamp. This allows low-cost embedded devices to perform progressive trigger calibration of periodic tasks even under conditions of network outage, lack of backup RTC batteries, or large temperature drift of ordinary crystal oscillators. This solves the problems of traditional network time synchronization failure due to network outages, high cost of hardware clock enhancement, invisible scheduling deviations caused by load fluctuations, and task avalanche caused by concentrated corrections. Therefore, this application enables the drift compensation process to operate collaboratively with the task scheduling process, gradually absorbing deviations and preventing the scheduler's instantaneous load from being amplified by a one-time correction.

[0029] In one implementation, the method operates as a scheduling calibration service. This scheduling calibration service can reside in a user-space monitoring process. It can also reside in a low-priority maintenance task of the real-time operating system, or in a periodic maintenance branch within the bare-metal main loop; it can also reside in the kernel-space scheduler bypass logic. To avoid affecting the calibrated task, the scheduling calibration service has a lower priority than control tasks, communication heartbeat tasks, and watchdog tasks, and its own execution time is included in the calibration performance evaluation. The method does not require changing the system global time, nor does it require modifying the business logic of application tasks; for application tasks, they still register the theoretical trigger time according to the original cycle, and the calibration logic only updates the corresponding correction trigger timestamp before the scheduler prepares to retrieve the next batch of tasks to be executed.

[0030] S100 acquires system tick count deviation, scheduling tick deviation and processor load intensity within a preset sampling period to form clock characteristic data, and determines the global clock drift reference value based on the theoretical trigger time and actual trigger time of the timed task.

[0031] like Figure 2 As shown, this stage is used to establish the data foundation for drift detection. Let the sampling period be... This can be provided by the initial configuration or updated by feedback during subsequent performance evaluation phases. In resource-constrained microcontrollers, Can be taken to In equipment with short task cycles or rapid temperature fluctuations, It can be shortened to to .

[0032] In the During the next sampling, the system tick count deviation is first acquired. For devices running Linux-like systems, the cumulative tick value maintained by the kernel or a high-resolution counter can be read; for devices running real-time operating systems, the system tick counter, the SysTick register derived count value, or the scheduler tick cumulative value can be read; for bare-metal systems, the hardware timer count value can be read. Let the actual tick increment between two adjacent samples be . The theoretical tick increment obtained based on the nominal tick frequency and sampling period is: The system tick count deviation can then be expressed as: When it is inconvenient for the system to directly calculate the nominal tick increment, the relative change between the cumulative tick value and the external task trigger count can be recorded, and this relative change can be used as an equivalent representation of the system's tick count deviation.

[0033] Secondly, the scheduling tick skew is obtained. Scheduling tick skew reflects the deviation of the actual time interval between task triggering by the scheduler under the current load. In implementation, lightweight timestamp probes can be deployed when the scheduler retrieves a task, the task enters the ready queue, the task actually begins execution, or a periodic timer interrupt occurs. Let the actual time interval between adjacent scheduling events be... The theoretical scheduling cycle time is Then the scheduling cycle deviation is For low-end devices without a high-precision timestamp source, this deviation can be approximated by the number of ticks spanned by the scheduling event, the difference between the ticks from task readiness to execution, or the difference between the actual number of executions and the theoretical number of executions of the control loop.

[0034] Next, obtain the processor load strength. In Linux-like systems, this can be calculated based on a combination of processor active cycles, idle cycles, run queue length, and context switching frequency. In real-time operating systems, it can be calculated based on the proportion of idle tasks, interrupt occupancy count, number of ready tasks, and number of preemption attempts by high-priority tasks. In bare-metal systems, it can be calculated based on the main loop idle branch count, timer interrupt occupancy proportion, and peripheral interrupt queue length. For ease of subsequent prediction, Normalized to to ,in Indicates that the area is nearing idle. This indicates near full load. If the system cannot provide complete load metrics, at least the inverse ratio of idle count can be used as a measure of processor load intensity.

[0035] The above three dimensions are assembled into a clock feature vector: In the implementation, the clock feature vector can be stored as a fixed-length structure, containing the sampling sequence number, sampling time, tick skew, scheduling tick skew, processor load intensity, sampling validity flag, and parameter version number. The sampling validity flag indicates whether the current sampling was affected by an interrupt storm, abnormal blocking, or debugging pause. The parameter version number ensures that the sampling result and subsequent prediction parameters are in the same closed-loop cycle.

[0036] After obtaining the clock characteristic data, an offset table is established for the target timing task set. For the first... A timed task, recording its theoretical trigger time. and actual trigger time Obtain the single-task offset The theoretical trigger time can be derived from the period configuration during task registration, or it can be obtained by adding the task period to the previous theoretical trigger time. The actual trigger time can be the moment when the task transitions from the ready queue to the running state, or it can be the timestamp at the task callback function entry point. For tasks triggered by interrupt service routines, the actual trigger time can be the moment when the task is submitted to the scheduling queue.

[0037] Multiple single-task offsets should not be simply averaged. Different tasks have different levels of business importance, cycle lengths, and allowable jitter ranges; therefore, weights must be used to differentiate them. Let the first... The weight of each task is Then the global clock drift reference value can be expressed as Weight The weighting can be determined by task priority, task cycle, control loop sensitivity, and security attributes. High-priority control tasks, watchdog tasks, and critical communication heartbeat tasks can receive higher weightings; log tasks, status reporting tasks, and low-frequency maintenance tasks can receive lower weightings.

[0038] To avoid transient jitter contaminating the global baseline, Perform sliding window filtering. The sliding window can save the most recent... Secondary effective reference value, The value can be between 5 and 20. If the offset of a single task significantly deviates from the midpoint of the window, and the corresponding task simultaneously displays an abnormal blocking flag, a debug pause flag, or a peripheral interrupt accumulation flag, then this offset is downweighted in this round of calculation, rather than being directly used to amplify drift judgment. This processing can avoid a single occasional blocking event being misjudged as hardware clock drift. The filtered output is denoted as... It serves as the input for subsequent load coupling drift prediction.

[0039] In one specific implementation, the offset table is stored using a circular buffer, retaining the most recent 3 to 8 trigger records for each task. Entries in the circular buffer include the task identifier, theoretical trigger time, actual trigger time, task priority, periodic configuration, trigger source, and exception flag. After each sampling, the calibration logic only processes newly written trigger records, avoiding repeated traversal of the entire historical data. For a microcontroller with 128KBSRAM, if 10 periodic tasks are recorded, with 4 trigger records retained for each task, and each record estimated at 32 bytes, the offset table occupies approximately 1280 bytes, which is suitable for low-resource scenarios.

[0040] In another implementation, if the device has multiple timing task domains, such as a control domain, a communication domain, and a maintenance domain, the drift reference value within each domain can be calculated separately, and then a global clock drift reference value can be synthesized based on the domain priorities. Control domain drift is used to protect high-priority real-time tasks, communication domain drift is used to protect heartbeat and polling tasks, and maintenance domain drift is used for logging and self-test tasks. By aggregating within domains first and then between domains, it is possible to prevent significant delays in low-priority maintenance tasks from masking subtle deviations in high-priority control tasks.

[0041] The core data output in the S100 phase includes the clock feature vector sequence, the smoothed global clock drift reference value, and the task offset table; it also includes a sampling validity flag. These data collectively form the factual basis for subsequent predictions and corrections. If the S100 phase detects persistently invalid sampling data, such as debugging pauses or interruptions occurring in multiple consecutive sampling cycles, the current calibration will not perform trigger time correction; instead, it will only record the abnormal state and continue prediction only after sampling stabilizes.

[0042] S200, determine the clock drift rate based on the time series of the clock characteristic data, and combine the load change state and scheduling delay state to form a load coupling drift prediction result.

[0043] like Figure 3 As shown, the inputs to stage S200 are the clock feature vector sequence output from stage S100, the smoothed global clock drift reference value, the sampling validity flag, and the parameter version number. The goal of this stage is not simply to amplify or reduce the current offset, but to estimate the trend of continued drift expansion in the next calibration cycle, incorporating processor load changes and scheduling latency status into the prediction. Through this processing, the system can distinguish between stable drift caused by long-term hardware clock offsets, transient scheduling latency caused by short-term blocking under high load, and drift rate changes caused by sudden load fluctuations.

[0044] In one implementation, the original drift rate is first determined based on the change in the global clock drift reference value between two consecutive iterations, and then an exponentially weighted moving average is applied to this original drift rate. Let the first... The smooth drift reference corresponding to the next sampling is The sampling period is The original drift velocity can then be expressed as Let the drift rate estimate of the previous round be... The smoothing coefficient is Then the drift rate in this round can be expressed as .in, It can be between 0.1 and 0.4. Smaller values... This makes the output smoother, suitable for devices with low loads and slow temperature changes; larger... It enables faster output response and is suitable for scenarios with frequent load changes or rapid equipment temperature rise.

[0045] Relying solely on It still cannot accurately reflect scheduling bias. Embedded devices experience processor load in situations involving communication bursts, dense peripheral interruptions, or concentrated control calculations. This will increase the time the scheduler spends between task expiration and actual execution. Therefore, a load fluctuation factor is introduced. In one embodiment, ,in This represents the load sensitivity coefficient. The reason for using a squared term is that small changes in the low-load range usually do not significantly affect task triggering, while the same change in the high-load range may cause a sharp increase in scheduler latency. The squared term allows the model to have a stronger response in the high-load range.

[0046] Furthermore, the magnitude of load variation between adjacent samples is calculated. If the processor load rapidly increases from a low value to a high value, the prediction sensitivity should be increased in advance, even if the current global drift baseline value has not yet increased significantly. The load-coupled drift rate can be expressed as... ,in This represents the load change sensitivity coefficient. If the predicted drift amount needs to be output, then the prediction time span is set to... and obtained . and It can be provided by the initial configuration, or it can be updated by the S500 stage based on the feedback of calibration performance indicators.

[0047] Scheduling delay status also participates in prediction correction. Scheduling cycle deviation has already been obtained in phase S100. If the deviation continues to increase positively over multiple consecutive sampling periods, it indicates that the actual triggering of the task is consistently later than the theoretical triggering. In this case, the prediction model marks the scheduling delay state as a delay amplification and allows the fine-tuning calculation phase to allocate compensation in advance. If the scheduling tick deviation increases abruptly only in a single sample, and that sample also has an interruption / blocking or debugging pause flag, the prediction model treats it as a transient anomaly, reducing the contribution of that sample to the prediction result.

[0048] During periods of high load, the model behaves with accelerated response. A period of high load can be defined by… The following are used to determine priority levels: the run queue length exceeds the task domain threshold, the context switching frequency exceeds a certain multiple of the window average, or the number of preemptions by high-priority tasks continues to increase. After entering a high-load period, the prediction model improves... , or At least one of these factors ensures that drift prediction results reflect the current operating status more quickly. To prevent overcompensation, the increase can be limited to the range allowed by the parameter table, and each parameter change must include the parameter version number.

[0049] During periods of low load, the model behaves with smooth output. A low load period can be defined by... Furthermore, the load variation is relatively small. In this case, the scheduler latency mainly comes from hardware clock skew and a small amount of system jitter. The predictive model reduces its response sensitivity, making the output closer to the long-term drift trend. This processing can avoid frequent changes in the compensation direction due to small jitters during low-load phases, thereby reducing the back-and-forth oscillations at the trigger time of scheduled tasks.

[0050] In one data structure embodiment, stage S200 maintains a prediction status table. The prediction status table includes the most recent smoothed drift rate, load sensitivity coefficient, load change sensitivity coefficient, scheduling delay status, prediction confidence, outlier count, and parameter version number. The prediction confidence indicates whether the current prediction round is suitable for entering stage S300; the prediction confidence decreases when the number of consecutive valid samples is insufficient, the proportion of outliers is too high, or the parameter version is being switched. If the prediction confidence is lower than a preset threshold, stage S300 can choose to perform delay compensation or only perform conservative fine-tuning.

[0051] For example, on an industrial controller using a common quartz crystal oscillator, the scheduling calibration service is... Sampling. Idle phase Approximately 0.18, the predictive model maintains a smooth output; when communication polling and PID control calculations occur simultaneously, It rose to 0.76, and The increase in compensation significantly improves the model's predictive sensitivity, allowing for earlier adjustments in subsequent fine-tuning phases. This compensation is not applied all at once to all tasks; instead, it is broken down into multiple fine-tuning segments by the S300 phase.

[0052] In the multi-condition identification embodiment, the S200 stage can further stratify the operating state. The first type is a stable low-load condition, characterized by low processor load intensity, small scheduling tick deviation, and consistent task offset changes. Under this condition, the prediction model focuses on long-term drift trends to avoid altering the compensation direction due to slight early or late arrivals or departures of individual tasks. The second type is a stable high-load condition, characterized by consistently high processor load intensity but small load fluctuations. Under this condition, scheduler latency is persistent, and the prediction model increases the basic load coupling weight while maintaining parameter smoothness to avoid frequent oscillations on high-load platforms. The third type is a load mutation condition, characterized by a rapid increase or decrease in processor load intensity within a short period, with synchronized changes in run queue length and context switching frequency. Under this condition, the prediction model increases its sensitivity to load changes and shortens the prediction window, enabling the compensation strategy to anticipate impending trigger deviations. The fourth type is an abnormal blocking condition, characterized by a sudden increase in scheduling tick deviation that cannot be explained by load intensity or task queue status. Under this condition, the prediction model reduces the sample weights and submits the samples to the S500 stage for anomaly attribution.

[0053] In devices with extended sensor data, the predictive model can also receive temperature estimates, power supply voltage states, or sleep / wake-up counts as auxiliary features. Frequency deviations of conventional crystal oscillators and on-chip RC oscillators may vary with temperature, and low voltage conditions may also affect timer stability. These auxiliary features do not replace system tick count skew, scheduling tick skew, and processor load intensity; rather, they are used to explain the sources of drift rate variations. For example, if temperature changes are significant but load changes are not pronounced, the model can attribute drift variations more to hardware clock temperature drift; if temperature is stable but load and scheduling latency increase simultaneously, the model can attribute drift variations more to scheduling congestion. This attribution result is used to adjust parameters without altering the basic closed-loop process defined in the claims.

[0054] The prediction confidence score can be calculated using a component-based scoring method. A higher number of valid samples results in a higher confidence score; a higher proportion of outlier samples results in a lower confidence score; confidence increases when the load state and scheduling delay state are aligned; confidence decreases when the prediction direction is continuously opposite to the posterior offset direction of the previous calibration cycle. The confidence score can be mapped to three prediction levels: conservative, normal, and aggressive. At the conservative level, the S300 stage applies only minor fine-tuning or only accumulates residuals; at the normal level, the S300 stage executes according to the current segmentation strategy; at the aggressive level, the S300 stage can use higher initial compensation weights, but still must not exceed the single-cycle correction amplitude limit. Through confidence level grading, the output of the prediction model will not directly and unconstrainedly change the task queue, but will always be constrained by the fine-tuning and anti-avalanche stages.

[0055] The S200 stage outputs the load coupling drift prediction results, prediction confidence, and an updated prediction state table. The load coupling drift prediction results can be a predicted drift amount or a combination of drift rate and future calibration cycle length. Understandably, regardless of the representation used, the corresponding sampling window, parameter version, and abnormal sample handling records should be retained for retrospective evaluation in the S500 stage.

[0056] S300, the predicted drift amount corresponding to the load coupling drift prediction result is divided into multiple fine-tuning segments, and the theoretical trigger time of the timed task is corrected according to the fine-tuning segments to obtain the corrected trigger timestamp, wherein the correction magnitude within a single scheduling cycle is constrained by a preset ratio upper limit.

[0057] like Figure 4 As shown, stage S300 transforms the load coupling drift prediction result output from stage S200 into a fine-tuning sequence that can be applied to the trigger timestamps of timed tasks. If the predicted drift amount is directly applied to the task queue at once, multiple periodic tasks may be moved forward or backward at the same time, causing concentrated triggering. To avoid this problem, this application splits the predicted drift amount into multiple fine-tuning segments and executes them progressively across multiple scheduling cycles.

[0058] Let the predicted drift obtained in stage S200 be... Fine-tuning the number of segments is . This can be provided by the initial configuration or updated by the S500 phase based on scheduling latency increments and resource overhead feedback. In scenarios where short-cycle tasks account for a high proportion, this is particularly relevant. A larger value can be chosen, such as 10 to 20, to make each correction smaller; in scenarios with long task cycles and slow drift accumulation, A value of 5 to 10 can be used to reduce the cost of maintaining calibration status. These are not fixed parameters within the protected boundary, but rather adjustable implementation parameters.

[0059] In one implementation, the fine-tuning segments are allocated using a linearly decreasing method. The compensation amount of each fine-tuning segment can be expressed as: The linear decreasing approach involves a larger amount of compensation in the first few scheduling cycles, gradually converging in subsequent cycles. This approach is suitable for scenarios where the drift is already significant and requires rapid recovery. If the system is under high load, this approach can increase the initial compensation intensity without exceeding the single-cycle correction limit.

[0060] In another implementation, the fine-tuning segments are allocated using an exponential decay method. The compensation amount of each fine-tuning segment can be expressed as: ,in This represents the attenuation coefficient. The exponential attenuation method is suitable for scenarios with rapid drift changes but high requirements for task triggering stability. Its initial compensation is more pronounced, while the subsequent compensation tends to be smoother. If the equipment is under low load, an approximately uniform distribution method can also be used, ensuring that each scheduling cycle experiences a similar amount of compensation.

[0061] It should be noted that regardless of the allocation method used, the correction magnitude within a single scheduling cycle is subject to an upper limit. Let the current scheduling cycle be... The preset ratio upper limit is Then it should satisfy In one embodiment, A value of 0.2 can be used, meaning the single-cycle correction amount cannot exceed 20% of the current scheduling cycle. If a fine-tuning segment exceeds this upper limit, the excess portion will be written into the remaining compensation amount. This process is then rolled over and incorporated into subsequent calibration cycles. This prevents abrupt changes in task trigger timing caused by excessive compensation in a single instance.

[0062] Understandably, the drift direction also needs to be addressed. If This indicates that the actual triggering of tasks is generally later than the theoretical triggering. Fine-tuning the logic can appropriately advance the corrected trigger timestamps for some tasks; if... This indicates that the actual triggering of a task is generally earlier than the theoretical triggering, and the fine-tuning logic can appropriately shift the trigger timestamp backward. For tasks with different cycles, shifting forward or backward does not directly change the task cycle configuration, but rather changes the trigger timestamp of the current cycle or several subsequent cycles. After the drift converges, the task continues to calculate the theoretical triggering time according to the original cycle.

[0063] For the One task, theoretically triggered at time [time missing]. , No. Each fine-tuning sub-segment is Then the correction trigger timestamp can be represented as .in, Task weights can be adjusted based on task priority, task duration, and allowable fluctuation range. High-priority tasks are controlled by... It can be higher, allowing it to approach the calibration target more quickly; for jitter-sensitive but non-safety-critical tasks, The trigger time can be lower, making the changes in trigger time smoother; for logs and maintenance tasks, low-priority delay processing can be performed only when the task queue is reordered.

[0064] In one implementation, the fine-tuning calculation module maintains a fine-tuning status table. This table includes at least the task identifier, the current fine-tuning segment number, and the number of fine-tuning segments; it also includes the current sub-segment compensation amount, the remaining compensation amount, the task correction weight, the timestamp of the last correction trigger, and the parameter version number. This table is updated whenever the S500 phase is updated. , When load coupling parameters are used, the fine-tuning state table is not immediately cleared entirely, but rather a smooth transition is performed at the parameter version switching point. If the state table is cleared directly, the remaining compensation amount from the previous round may be lost, which could cause a jump in the triggering time.

[0065] Modifying the trigger timestamp also needs to satisfy the task's own periodic constraints. For tasks with a period of... If the corrected trigger timestamp of a task is too close to the previous actual trigger time, there is a risk that the task may be retried before it is completed. To address this, a minimum task interval can be set for each task. ,Require If this condition is not met, the correction amount for the current task is truncated, and the truncated portion is added to the remaining compensation amount. For the Watchdog feeding task, a maximum allowed backswing time can also be set to ensure that the backswing compensation does not violate safety constraints.

[0066] Since low-end embedded devices may only have tick-level time resolution, fine-tuning calculations must also handle rounding errors. If the amount is less than one tick, the small compensation can be accumulated in the fractional residual register, and then applied after the accumulated value reaches one tick. This avoids rounding to 0 in each round of compensation and also avoids frequent rewriting of the task queue. The fractional residual register also needs to be signed; positive and negative residuals cannot be mixed and canceled out unless they belong to the same task domain and the same parameter version.

[0067] For example, the scheduling cycle time of a certain device is The predicted drift for this round is The number of fine-tuning segments is set to 10, with a maximum ratio of 20%. If a linear decreasing method is used, the initial calculated compensation amount for the first segment may exceed [a certain threshold]. The compensation amount that actually applies to the current scheduling cycle is truncated to... The remaining portion rolls over to subsequent cycles. For resolutions of... The system Unable to express it directly, the fine-tuning calculation module treats it as a cumulative residual, forming a single value after five consecutive cycles. Level correction. This process still belongs to segmented fine-tuning because the task triggering time was not changed drastically all at once.

[0068] At the end of phase S300, the fine-tuning calculation module outputs a set of corrected trigger timestamps, a fine-tuning status table, and remaining compensation. The set of corrected trigger timestamps does not directly determine the task execution order; it still needs to enter phase S400 for queue rearrangement and conflict resolution. This design is because the corrected trigger timestamps calculated by multiple tasks may be close to each other. If they are directly submitted to the scheduler without conflict detection, there is still a risk of concentrated triggering.

[0069] S400, rearrange the timed task queue according to the corrected trigger timestamp, and when the trigger times of multiple timed tasks fall into the same conflict time window, perform anti-avalanche scheduling based on task priority and minimum safe interval.

[0070] The S400 stage receives the set of corrected trigger timestamps output from the S300 stage and transforms this set into a task execution queue that the scheduler can consume. The purpose of this stage is to prevent multiple tasks, after segmented fine-tuning, from being triggered at close intervals. In other words, S300 addresses the problem of "how to apply the correction gradually," while S400 addresses the problem of "how to prevent the corrected tasks from being executed in a concentrated manner."

[0071] In one implementation, the scheduling reordering module first sorts the candidate tasks into a queue based on their modified trigger timestamps. The sorting rule can follow a time-priority principle, placing tasks with earlier trigger timestamps at the front of the queue. When multiple tasks have the same modified trigger timestamp, a secondary sorting is performed based on task priority, task security attributes, and task cycle time. If the device's existing scheduler already uses a fixed priority strategy, the scheduling reordering module does not replace the original priority rules but instead adds a trigger timestamp reorganization process before the original rules to ensure a more even distribution of task arrival times.

[0072] Conflict detection can be performed using the interval between adjacent task triggers. Let the difference in correction trigger timestamps between two adjacent tasks after sorting be denoted as . The minimum safe interval is .like If so, then the two tasks are determined to fall into the same conflict time window. It can be determined based on scheduling cycle time, task switching overhead, shortest task execution time, and interrupt response requirements. In one embodiment, Can be taken to In systems with coarser tick granularity, one to two ticks can also be used.

[0073] To reduce computational overhead, a time-bucket approach can be used for conflict detection. The scheduling and reordering module divides a calibration period into multiple time buckets, each with a width equal to or slightly greater than [the specified value]. Tasks whose trigger timestamps fall within the same time bucket are considered potentially conflicting tasks. For tasks at the boundaries of adjacent time buckets, the actual trigger interval is calculated additionally. This method avoids comparing all tasks pairwise, making it suitable for embedded systems with a large number of tasks but limited processor resources.

[0074] After determining the set of conflicting tasks, priority-based triggering is implemented. Each task can have a base priority, a real-time level, a security level, and a delay level. High-priority control tasks, watchdog tasks, and critical communication tasks typically retain their corrected trigger timestamps or are only allowed to be shifted back by a very small margin; low-priority logging tasks, status reporting tasks, and background self-check tasks can be shifted back according to their priority differences. The shift amount is not considered a loss of calibration amount but is written into the task's delay compensation record and considered uniformly in the next round of fine-tuning or queue reordering.

[0075] When inserting the minimum safety interval, the scheduling reordering module starts with the highest priority task in the conflicting task set and assigns trigger positions to subsequent tasks in sequence. If the trigger timestamp of the first task is... Then the trigger timestamp of the second task must not be earlier than The third task must not be earlier than the final trigger timestamp of the second task plus... For tasks of the same priority, the order can be determined based on factors such as shorter task cycles, fewer recent delays, or stable task identifiers. Stable sorting can prevent the same group of tasks from repeatedly swapping positions in multiple calibration rounds.

[0076] When there are many conflicting tasks, the scheduler's time slices or task delivery rhythm can be temporarily adjusted. For example, if the number of tasks in the same time bucket exceeds a preset threshold, the scheduling reordering module can deliver low-priority tasks to the ready queue in batches, or temporarily shorten the time slices of low-priority tasks, allowing high-priority tasks to obtain processors faster. This process is part of the avalanche prevention strategy, but it is not a necessary step in all implementations. In systems with strict real-time requirements, time slice adjustments should be constrained by the operating system's scheduling policy and should not disrupt the priority of safety-critical tasks.

[0077] To prevent low-priority tasks from being postponed indefinitely, a delay debt mechanism can be implemented in the S400 phase. Each task maintains a delay debt value. When the mission is postponed due to avalanche prevention scheduling, Add; when the task is triggered on time or ahead of schedule in a subsequent cycle, Reduce. If a low-priority task If the task exceeds the allowed threshold, its ranking among tasks of the same priority level will be increased without affecting the safety constraints of higher-priority tasks. This mechanism can prevent logging, status reporting, and maintenance tasks from completely losing their execution opportunity due to prolonged low priority.

[0078] Task queue reordering also needs to handle the uncertainty of task execution time. For tasks with measurable execution time, the highest percentile value of the most recent execution times can be used as the estimated task occupancy value, and this estimated value is added to the minimum safety interval during conflict detection. For tasks with unmeasurable execution time, a conservative interval can be set according to the task type. If a task's actual execution time exceeds the estimated value, the S500 phase will include the excess in the scheduling delay increment and feed back the impact on subsequent tasks. Or fine-tune the number of segments.

[0079] In one industrial PLC implementation, the data acquisition task cycle is: The PID control task cycle is The Modbus communication task cycle is The status log task cycle is When the correction trigger timestamp generated in the S300 phase causes the data acquisition task and the communication task to fall into the same... During the time window, the S400 phase retains the trigger position of the data acquisition task, shifts the communication task to a minimum safe interval, and writes this shift amount into the communication task delay compensation record. If status log tasks conflict simultaneously, the status log task is scheduled to be placed in a later idle bucket.

[0080] In the safety window implementation, each task can also maintain an earliest allowed trigger time and a latest allowed trigger time. The earliest allowed trigger time is used to prevent tasks from executing prematurely due to forward compensation before input data is prepared, peripherals have completed conversion, or the control quantity of the previous cycle has stabilized; the latest allowed trigger time is used to prevent tasks from missing control, communication, or safety maintenance windows due to backward compensation. The scheduling reordering module checks both boundaries simultaneously when inserting the minimum safety interval. If a task cannot be reordered within the safety window, the task is marked as either not allowed to be moved backward or not allowed to be moved forward, and the undigested compensation amount is handled by subsequent cycles, rather than forcibly violating the task safety boundaries.

[0081] Queue submissions also need to guarantee atomicity. If the scheduling reordering module is interrupted by a high-priority interrupt during task queue updates, a mixed state may occur where some tasks use the old trigger timestamp and others use the new trigger timestamp. To avoid this problem, a double-buffered queue can be used. The calibration logic performs sorting, conflict detection, and avalanche prevention in the background buffer; after the background buffer verification passes, the foreground queue pointer is switched using a short critical section. For systems that cannot use double buffering, queue version numbers can also be used, allowing the scheduler to consume only queue records with the same version number.

[0082] In long-running scenarios, the S400 phase can also track the number of times tasks are moved forward, backward, or truncated. If a task is consistently moved forward, it indicates a potential persistent deviation between its theoretical cycle and the current drift trend; if a task is consistently moved backward, it suggests its priority or task domain configuration may be too low; if a task is frequently truncated, it indicates the single-cycle correction magnitude or minimum safety interval needs reassessment. These statistics do not directly alter the current queue but are submitted to the S500 phase as part of the calibration performance metrics.

[0083] The S400 stage outputs the scheduler execution queue, conflict task record, delay debt table, and queue rearrangement results after avalanche protection processing. The scheduler execution queue is submitted to the original scheduler or task delivery logic; the conflict task record and delay debt table are submitted to the S500 stage to evaluate whether the current calibration strategy is too aggressive and whether it is necessary to increase the number of fine-tuning segments, expand the minimum safety interval, or reduce the single-cycle correction magnitude.

[0084] S500 forms a calibration performance index based on the task trigger offset dispersion, scheduling delay increment and processing resource overhead within the calibration period, and adjusts the sampling period, fine-tuning the number of segments and load coupling parameters based on the calibration performance index.

[0085] like Figure 6 As shown, the S500 phase is used to evaluate whether the aforementioned sampling, prediction, fine-tuning, and avalanche prevention scheduling have achieved the expected results, and feeds the evaluation results back to the next calibration cycle. Without the S500 phase, the system can only operate according to fixed parameters; when equipment load, temperature, number of tasks, and runtime change, the fixed parameters may be too sluggish or too aggressive. This application incorporates compensation accuracy, scheduling stability, and resource overhead into a closed loop through calibration performance indicators.

[0086] In one implementation, calibration performance metrics include task trigger offset dispersion, scheduling latency increment, and processing resource overhead. Task trigger offset dispersion can be represented by offset variance, mean absolute offset, maximum offset, or high quantile offset. Let the first... The offset of each task within the calibration period is The average offset is Then the variance of the offset can be expressed as ,in This represents the number of tasks included in the statistics. A larger variance indicates a more uneven distribution of trigger offsets among different tasks, which may require increasing the sampling frequency or the number of fine-tuning segments.

[0087] The scheduling delay increment characterizes the additional impact of calibration logic on the original scheduler. This metric can be calculated by the difference in waiting time between task due date and actual execution before and after calibration, or by combining the number of conflicting tasks, the cumulative value of delay debt, the number of times low-priority tasks are moved back, and the congestion level of the time bucket. If the scheduling delay increment continues to increase, it indicates that the current fine-tuning and reordering strategies are too concentrated, and the number of fine-tuning segments can be increased in the S500 phase. Reduce the single-cycle correction ratio Or increase the minimum safety interval .

[0088] Processing resource overhead is used to constrain the computational and memory usage of the calibration logic itself. Processing resource overhead can include the execution time of a single calibration service run, sampling buffer usage, and task offset table usage; it can also include prediction state table usage and queue reordering time. In low-end microcontrollers, if the calibration service itself consumes too much processor time, it may offset the scheduling stability benefits it provides. Therefore, when processing resource overhead... When the overhead threshold is exceeded, the S500 phase can be extended. Reduce the sliding window length, decrease the number of time buckets, or temporarily disable some low-value statistical items.

[0089] Optionally, in the S500 stage, the offset variance, scheduling delay increment, and processing resource overhead are first mapped to dimensionless indices, and then the cost function is constructed. .in, This represents the normalized variance of the offset. This represents the normalized scheduling delay increment. This represents the normalized processing resource overhead. , and This is a dimensionless weighting coefficient. For equipment prioritizing stability control, it can improve... and For battery-powered devices with low real-time requirements, it can improve... The cost function does not require complex floating-point calculations. In devices without floating-point units, it can be implemented using fixed-point numbers, lookup tables, or hierarchical scoring methods.

[0090] Parameter feedback updates can employ regular updates, gradient descent updates, or a hybrid approach. Examples of regular updates include: if the offset variance increases for three consecutive calibration periods, shorten the sampling period or increase the load sensitivity coefficient; if the number of conflicting tasks increases continuously, increase the number of fine-tuning segments or expand the minimum safety interval; if processing resource overhead exceeds a threshold, extend the sampling period or reduce the window length. Examples of gradient descent updates include: based on the cost function... , , and Based on the approximate trend of change, we can make small adjustments in the direction that reduces the value of the product.

[0091] To avoid frequent parameter oscillations, the S500 phase employs a parameter versioning and smooth activation mechanism. Each time a new parameter is generated, it is first written to the candidate parameter area and marked with a candidate version number. Only when a candidate parameter reduces the cost function over several consecutive calibration cycles, or at least does not cause a deterioration in scheduling latency increments, is it promoted to the effective version. If a candidate parameter leads to increased offset variance, an increase in the number of conflicting tasks, or excessive processing resource overhead, it reverts to the previous stable version. This mechanism prevents the system from repeatedly switching parameters during sudden load changes.

[0092] In scenarios involving power outages, restarts, or abnormal resets, the S500 phase also handles calibration state recovery. Recoverable states include the most recent stable parameter version, sliding window summary, remaining compensation amount, and delay debt table; it also includes a task offset statistical summary and anomaly sample count. After recovery, the system does not immediately perform large-scale compensation but instead enters a conservative recovery period. During this period, the single-cycle correction magnitude is reduced, and prediction sensitivity is limited until a sufficient number of valid samples are collected. This process avoids over-correction that occurs when the device is first started due to inconsistencies between historical states and current load.

[0093] like Figure 7 As shown, the system of this application includes a drift sampling module, a drift prediction module, a fine-tuning calculation module, a scheduling reordering module, and a performance evaluation module. The drift sampling module periodically acquires system tick count deviation, scheduling tick deviation, and processor load intensity, and maintains a task offset table. The drift prediction module reads the clock feature vector sequence and the global clock drift reference value, and outputs the load-coupled drift prediction result. The fine-tuning calculation module divides the predicted drift amount into multiple fine-tuning segments, generates a correction trigger timestamp for each timed task, and applies a preset proportional upper limit constraint to the correction magnitude within a single scheduling cycle. The scheduling reordering module constructs a scheduling execution queue based on the correction trigger timestamp and performs avalanche prevention scheduling when trigger conflicts occur. The performance evaluation module statistically analyzes calibration performance indicators and feeds back the updated calibration parameters to the aforementioned modules.

[0094] In Linux-like systems, the drift sampling module can obtain input data through kernel counters, task scheduling events, and processor statistics. Sampling data can be written to shared memory and protected by semaphores or lightweight locks; trigger timestamps can be passed via message queues or scheduler extension interfaces; the parameter table can be protected by read-write locks to ensure that the sampling module does not encounter a half-updated state when reading parameters. In real-time operating systems, the drift sampling module can run as a low-priority task, the scheduling reordering module can operate between timer callbacks and the task ready queue, and the parameter table can be protected by short critical sections with interrupts disabled or mutexes.

[0095] In a bare-metal system, the system implementation can be more lightweight. The drift sampling module executes during the idle branch of the main loop or after a timer interrupt. The drift prediction module and the fine-tuning calculation module update the state at a fixed frequency. The scheduling and reordering module maintains only a small array sorted by trigger timestamps. If the number of tasks does not exceed 16, insertion sort can be used to reorder the queue; if the number of tasks is large, a min-heap or time wheel structure can be used. Regardless of the data structure used, the technical approach of this application—drift compensation through load-coupled prediction, piecewise fine-tuning, and avalanche-resistant reordering—remains unchanged.

[0096] Data transfer between modules can take the following forms: the drift sampling module outputs sampling records. It includes sampling sequence number, clock feature vector, task offset summary, and anomaly flag; the drift prediction module outputs prediction records. It includes predicted drift, prediction confidence, load status, and parameter version; the fine-tuning calculation module outputs correction records. It includes the task identifier, correction trigger timestamp, remaining compensation amount, and decimal residual; the scheduling reordering module outputs scheduling records. It includes the final trigger timestamp, conflict window, delayed debt, and execution order; the performance evaluation module outputs parameter records. This includes the sampling period, the number of fine-tuning segments, load coupling parameters, and safety intervals. These records can be stored as a circular buffer to reduce memory usage.

[0097] For devices with task domain divisions, the system can also set independent parameters for different task domains. For example, the control domain uses a shorter sampling period, higher task weight, and a stricter minimum safety interval; the communication domain uses a medium sampling period and stronger load coupling prediction; and the maintenance domain uses a longer sampling period and lower task weight. The performance evaluation module can first evaluate within the domain and then coordinate global parameters. This protects critical tasks while preventing low-priority tasks from being sacrificed in the long term.

[0098] like Figure 8 As shown, in an industrial PLC application verification embodiment, the hardware platform uses a main frequency of [missing information - likely a specific frequency range]. The ARM Cortex-M4 has on-chip memory resources including The device uses SRAM, lacks an RTC backup battery, and employs a standard quartz crystal oscillator. The operating system is FreeRTOS, and the scheduler tick frequency is [missing information]. The scheduled tasks include 10 periodic tasks, with periodic coverage. to The task types include data acquisition, PID control, Modbus communication, and watchdog maintenance. The initial sampling period for the scheduling calibration service is... And run it with low priority.

[0099] The verification scenario is continuous. Operation was performed without network access. Comparative schemes included a no-calibration scheme, a scheme relying solely on network time synchronization, and a scheme employing the method described in this application. After network access was lost, the no-calibration scheme showed significant accumulated trigger offset within several hours, with short-cycle control tasks gradually deviating from the theoretical trigger point; the scheme relying solely on network time synchronization had a good baseline in the initial stage of network access loss, but could not continue to suppress weak local clock drift after losing the external time source; the scheme employing the method described in this application continuously compensated based on local clock characteristic data, load status, and scheduling delay during network access loss.

[0100] In this embodiment, continuous operation Afterwards, the average task trigger offset without calibration reached The maximum task trigger offset has reached The scheduling sequence was disordered 14 times, and task-driven avalanches occurred 3 times; the average task trigger offset of the scheme relying solely on network time synchronization reached [missing information]. The maximum task trigger offset has reached The scheduling sequence was disordered 7 times, and avalanche was triggered 2 times in the task set; the average task trigger offset of the scheme using the method in this application is maintained at Within the range, the maximum task trigger offset remains at Within the specified range, the number of scheduling sequence disruptions was 0, the number of avalanches triggered by concentrated tasks was 0, and the processor resource overhead was approximately [missing information]. The above data is only used to illustrate the effects of this embodiment and does not constitute a numerical limitation on other device platforms.

[0101] The results show that this application does not reduce drift by improving hardware clock accuracy, but rather by forming a sustainable compensation closed loop through local runtime data. The offset of an uncalibrated scheme accumulates over time, and network time synchronization schemes lose their ability to continue correcting after a network outage. In contrast, the method in this application can still adjust the calibration strategy based on actual task-triggered offsets, scheduling tick deviations, and load changes even without an external time source. Because the predicted drift is broken down into multiple fine-tuning segments, and the task queue undergoes anti-avalanche rearrangement, no transient congestion triggered by multiple tasks occurs during the calibration process.

[0102] In another embodiment, this application can be applied to battery-powered field sensor nodes. These nodes are normally in a low-power sleep state, periodically waking up to perform sampling and wireless transmission tasks. Due to temperature variations and low-cost oscillator errors, the wake-up cycle is prone to drift. Using the method of this application, the node records the theoretical and actual wake-up times after each wake-up, and incorporates battery voltage, temperature estimates, and processor load status as optional extended features in the prediction. If the wireless transmission task and the sensor preheating task conflict within the corrected time window, the avalanche prevention scheduling prioritizes the sensor preheating task and then postpones the wireless transmission task, thereby avoiding excessively high instantaneous current peaks.

[0103] In another embodiment, this application can be applied to an in-vehicle edge controller. In-vehicle devices may be located in underground parking lots, tunnels, or closed network environments where external time synchronization is unstable; simultaneously, vehicle startup, communication handshakes, and sensor initialization can cause significant load fluctuations. The load coupling drift prediction of this application can improve response sensitivity during load fluctuations, segmented fine-tuning can prevent a large number of periodic tasks from being simultaneously moved forward during the startup phase, and anti-avalanche scheduling can protect high-priority control tasks and watchdog tasks. Therefore, even under short-term network outages or long-term weak clock conditions, the device can maintain relatively stable triggering of timed tasks.

[0104] In one parameter boundary implementation, upper and lower limits are set for the sampling period, the number of fine-tuning segments, the load sensitivity coefficient, and the minimum safety interval. The lower limit for the sampling period is used to prevent the calibration service from preempting the processor too frequently, while the upper limit is used to prevent drift from going undetected for extended periods. The lower limit for the number of fine-tuning segments is used to prevent compensation from being too concentrated, while the upper limit is used to prevent the remaining compensation from being over-digested for too long. The lower limit for the load sensitivity coefficient is used to maintain the model's basic awareness of load changes, while the upper limit is used to prevent over-prediction during high-load phases. The lower limit for the minimum safety interval is used to ensure that task switching and interrupt responses have a buffer, while the upper limit is used to prevent low-priority tasks from being excessively postponed. These upper and lower limits can be set according to the number of tasks on the device, the shortest task cycle, the scheduling cycle time, and safety requirements.

[0105] Regarding anomaly handling, if the valid sampling flag obtained from continuous sampling is invalid, the S500 stage will not immediately increase the prediction sensitivity, but will instead record this state as insufficient data. In the insufficient data state, the S300 stage can only perform residual accumulation without making significant adjustments to the task trigger timestamp. If an interruption storm, peripheral device blockage, debugging pause, or abnormal increase in task execution time occurs, the task offset for that period will not be directly entered into the global drift baseline value, but will instead be entered into the anomaly sample list. The anomaly sample list retains the occurrence time, associated task, anomaly type, and offset size for subsequent determination of whether the anomaly is repetitive. If an anomaly occurs repeatedly within multiple calibration periods, it is no longer considered an occasional anomaly, but rather used as input for load-coupled prediction.

[0106] If the predicted drift is continuously opposite to the actual posterior offset direction, it indicates that the prediction model may be over-responding or the load coupling parameters are inappropriate. In this case, the prediction confidence should be reduced in the S500 stage, and the load sensitivity coefficient or load change sensitivity coefficient should be decreased. If the actual posterior offset direction is consistent with the predicted direction, but the offset decreases too slowly, it indicates insufficient compensation. The sampling period can be appropriately shortened, the initial fine-tuning weights increased, or the load coupling parameters increased. If the actual posterior offset decreases rapidly but the number of conflicting tasks increases, it indicates that the compensation is effective but the queue impact is too large. The number of fine-tuning segments should be increased or the minimum safety interval expanded, rather than continuing to increase the prediction sensitivity.

[0107] In resource-constrained devices, the status of each stage can be stored using fixed-length fields, with the field width determined by the platform word length, counter range, and number of tasks. Sampling records may include sampling sequence number, cumulative tick difference, scheduling tick difference, normalized load intensity, anomaly flag, and parameter version number. Task offset records may include task identifier, theoretical trigger tick, actual trigger tick, task priority, periodic tick, and anomaly flag. Prediction records may include drift rate fixed-point value, predicted drift fixed-point value, prediction confidence level, load status code, and parameter version number. Fine-tuning records may include task identifier, fine-tuning segment sequence number, remaining compensation tick, decimal residual, and correction trigger tick. Using fixed-length fields avoids dynamic memory allocation and reduces fragmentation risk.

[0108] If the system does not have a floating-point unit, you can , , , and All values ​​are converted to fixed-point numbers. For example, the normalized load intensity is represented as an integer from 0 to 1024, and the scaling factor is represented as an integer multiplied by 1024. After the multiplication calculation, the scale is restored by shifting it 10 bits to the right. Exponential decay allocation can be implemented using a lookup table, with entries pre-generated according to the commonly used number of fine-tuning segments; if storage space is more limited, only the linear decreasing allocation method can be retained. The above implementation does not change the technical logic of this application, but simply replaces the mathematical operations with equivalent calculations suitable for low-resource devices.

[0109] To ensure power-off recovery, stable parameter versions and necessary calibration states can be written to non-volatile memory. Writing does not need to be performed every sampling cycle to avoid increasing Flash erase / write cycles. The summary state can be written before the parameter version stabilizes, the remaining compensation amount falls below a threshold, or the device enters sleep mode. The summary state includes the stable parameter version, sliding window mean, most recent offset direction, remaining compensation amount, and a summary of delay debt. During recovery, the version number and checksum of the summary state are first verified. If verification passes, a conservative recovery period begins; if verification fails, factory default parameters are used, and the drift baseline is re-established after sufficient valid samples are collected.

[0110] In systems with a small number of tasks, a fixed array can be used for the scheduling execution queue. When inserting a task, the trigger timestamps are compared and elements are shifted from the tail of the array backward until an insertion position is found. For controllers with no more than 16 tasks, this approach is simple and predictable. For gateway devices with a large number of tasks, a binary heap, skip list, or time wheel can be used. The time wheel is suitable for a large number of periodic tasks; the trigger timestamps are first mapped to time slots, and then sorted by priority within the slots. Regardless of the structure chosen, the queue records should retain both the original theoretical trigger time and the final trigger time so that the S500 phase can calculate the scheduling delay increment.

[0111] In complex embedded systems, using a single global drift reference for all tasks may not be precise enough. Tasks can be divided into control, communication, sampling, and maintenance domains. The control domain includes closed-loop control, rapid sampling, and safety protection tasks; the communication domain includes heartbeat, bus polling, and protocol timeout tasks; the sampling domain includes sensor reading and data preprocessing tasks; and the maintenance domain includes logging, diagnostics, and remote status reporting tasks. Each task domain can calculate its intra-domain offset, the number of conflicting tasks, and the intra-domain latency debt, which are then aggregated by the performance evaluation module.

[0112] One advantage of task domain coordination is that it avoids lower-priority domains affecting the drift judgment of higher-priority domains. If the maintenance domain experiences significant delays due to log writing, while the control domain tasks remain stable, the global parameters should not significantly increase the prediction sensitivity due to maintenance domain anomalies. In this case, only the weight of the maintenance domain tasks needs to be reduced or the minimum safety interval of the maintenance domain adjusted. Conversely, if the control domain experiences continuous drift, even if the maintenance domain is generally stable, the global alert level should be increased, the sampling period shortened, and priority should be given to ensuring the fine-tuning compensation of the control domain tasks.

[0113] Task domains can also share some predicted states. For example, system tick count deviations caused by hardware clock temperature drift typically affect all task domains, so this deviation can be used as a globally shared variable; while scheduling tick deviations and latency debts are closer to the task domain state and can be maintained separately for each domain. By combining globally shared variables and intra-domain states, this application can simultaneously adapt to long-term hardware clock drift and local fluctuations in task load.

[0114] The above embodiments illustrate several implementation methods of this application. Those skilled in the art can substitute or combine the sampling data source, load intensity calculation method, fine-tuning allocation function, task queue data structure, and parameter feedback strategy without departing from the technical concept of this application. These substitutions or combinations, as long as they still utilize clock characteristic data to form a drift reference, combine load state to predict drift, correct the trigger timestamp through segmented fine-tuning, and form a closed loop through anti-avalanche rearrangement and performance feedback, all fall within the scope of the technical solution of this application.

[0115] 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.

[0116] 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 timed task weak clock drift adaptive calibration scheduling method, characterized in that, include: Within a preset sampling period, the system tick count deviation, scheduling tick deviation, and processor load intensity are acquired to form clock characteristic data, and the global clock drift reference value is determined based on the theoretical trigger time and actual trigger time of the timed task. The clock drift rate is determined based on the time series of the clock feature data, and combined with the load change state and scheduling delay state, a load coupling drift prediction result is formed. The predicted drift amount corresponding to the load coupling drift prediction result is divided into multiple fine-tuning segments, and the theoretical trigger time of the timed task is corrected according to the fine-tuning segments to obtain the corrected trigger timestamp. The correction magnitude within a single scheduling cycle is constrained by a preset upper limit. The timed task queue is rearranged according to the corrected trigger timestamp, and when the trigger times of multiple timed tasks fall into the same conflict time window, anti-avalanche scheduling is performed based on task priority and minimum safe interval. The calibration performance index is formed based on the task trigger offset dispersion, scheduling delay increment and processing resource overhead within the calibration period, and the sampling period, fine-tuning of the number of segments and load coupling parameters are adjusted based on the calibration performance index.

2. The method according to claim 1, characterized in that, The formation of the clock feature data includes: Obtain the deviation of the system tick cumulative value from the theoretical tick cumulative value, obtain the deviation of the actual tick between adjacent trigger events of the scheduler from the theoretical tick, and determine the processor load intensity based on the processor active cycle, idle cycle, run queue length and context switching frequency.

3. The method according to claim 1, characterized in that, The determination of the global clock drift reference value includes: Record the theoretical and actual trigger times of multiple timed tasks to obtain multiple single-task offsets; Weights are assigned to the offsets of the multiple single tasks according to the task priority, and a weighted drift characterization value is generated. The weighted drift characterization values ​​are subjected to sliding window filtering, and transient offsets that exceed the window's stable range are subject to weight reduction processing.

4. The method according to claim 1, characterized in that, The load coupling drift prediction results are formed by: The change in the global clock drift reference value obtained by continuous sampling is smoothly updated to obtain the clock drift rate; Improve drift prediction sensitivity when processor load intensity increases or load variation widens; When the processor load intensity decreases and the load variation amplitude decreases, the drift prediction sensitivity is reduced to ensure that the prediction output remains responsive and stable under load fluctuation scenarios.

5. The method according to claim 1, characterized in that, The multiple fine-tuning segments are allocated in a linear decreasing manner or an exponential decay manner, and the amount of trigger time correction generated by each fine-tuning segment in the current scheduling cycle is not greater than the preset ratio upper limit of the current scheduling cycle. If the predicted drift is not compensated within the current calibration period, the remaining compensation will be rolled over into subsequent calibration periods.

6. The method according to claim 1, characterized in that, The avalanche prevention scheduling includes: The trigger time interval between adjacent timed tasks is calculated based on the corrected trigger timestamp. When the triggering time interval is less than the minimum safety interval, the corresponding timed task is identified as a set of conflicting tasks; The conflicting task set is sorted according to task priority, so that high-priority tasks are kept at or close to their corrected trigger timestamps and low-priority tasks are delayed according to priority differences, so as to distribute the instantaneous load on the scheduler.

7. The method according to claim 1, characterized in that, The sampling period, the number of fine-tuning segments, and the load coupling parameters are adjusted based on the feedback from the calibration performance indicators, including: When the task trigger offset dispersion continues to increase, shorten the sampling period or increase the load coupling parameter; When the processing resource overhead exceeds the overhead threshold, extend the sampling period or reduce the load coupling parameter; when the scheduling delay increment increases, increase the number of fine-tuning segments or reduce the single-cycle correction amplitude, and make the updated calibration parameters take effect smoothly in the form of parameter versions.

8. The method according to claim 1, characterized in that, When the method is used in embedded devices without network time synchronization or without a high-precision real-time clock, the sampled data, drift reference, prediction parameters and fine-tuning state are stored as a recoverable calibration state. When the device is powered off and restarted or the scheduler is abnormally reset, the compensation process is restored based on the most recent valid calibration state, and the single-cycle correction amplitude is limited in the early stage of recovery to avoid the timed task triggering abrupt changes.

9. A timed task weak clock drift adaptive calibration scheduling system, characterized in that, include: The drift sampling module is used to acquire system tick count deviation, scheduling tick deviation and processor load intensity to form clock characteristic data, and to determine the global clock drift reference value based on the theoretical trigger time and actual trigger time of the timed task. The drift prediction module is used to determine the clock drift rate based on the time series of the clock feature data, and combine the load change state and scheduling delay state to form a load coupling drift prediction result; The fine-tuning calculation module is used to divide the predicted drift amount corresponding to the load coupling drift prediction result into multiple fine-tuning segments, and correct the theoretical trigger time of the timed task according to the fine-tuning segments to obtain the corrected trigger timestamp, and to make the correction magnitude within a single scheduling cycle constrained by a preset ratio upper limit. The scheduling rearrangement module is used to rearrange the timed task queue according to the corrected trigger timestamp, and when the trigger times of multiple timed tasks fall into the same conflict time window, it performs anti-avalanche scheduling based on task priority and minimum safety interval. The performance evaluation module is used to form a calibration performance index based on the task trigger offset dispersion, scheduling delay increment and processing resource overhead within the calibration period, and to adjust the sampling period, fine-tune the number of segments and load coupling parameters based on the calibration performance index.

10. The system according to claim 9, characterized in that, The drift sampling module and the drift prediction module transmit sampling data through a shared cache or message channel; The fine-tuning calculation module and the scheduling rearrangement module transmit the correction results through a trigger timestamp queue; The performance evaluation module writes the updated calibration parameters into a parameter table, which is read by the drift sampling module, the drift prediction module, and the fine-tuning calculation module, respectively, and the consistency of the parameter versions is ensured through a read-write protection mechanism.