A method for managing scheduled tasks, an embedded device, and a computer-readable storage medium.

CN122570091APending Publication Date: 2026-08-14ANHUI HELI CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-04-27
Publication Date
2026-08-14

AI Technical Summary

Technical Problem

采用链表结构的软件定时器方案需要在运行时动态申请和释放内存在嵌入式系统中容易产生内存碎片存在确定性风险

Benefits of technology

[0015]采用上述技术方案具有以下优点:

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122570091A_ABST
    Figure CN122570091A_ABST
Patent Text Reader

Abstract

This application discloses a timed task management method, an embedded device, and a computer-readable storage medium, relating to the field of embedded system technology. The method includes: defining a timed task control block structure type; defining a fixed-size structure array variable as a timed task pool and initializing each array element; traversing the timed task pool in an interrupt service routine periodically triggered by a base timer, decrementing the current count value for enabled timed tasks; when the current count value decrements to zero, setting the task ready flag to an active state, and resetting the current count value or modifying the task enable flag according to a task mode flag; polling the timed task pool in the system main loop, and calling the corresponding timed task function when the task ready flag is active. This method can reduce the risk of memory fragmentation and improve system responsiveness.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of embedded systems technology, and in particular to a timed task management method, an embedded device, and a computer-readable storage medium. Background Technology

[0002] In embedded systems and computer software applications, timed task management is a fundamental and crucial function. Both microcontroller systems and IoT devices widely require tasks to be executed on a timer. Current timed task management solutions mainly include pure hardware timers, operating system software timers, and traditional time wheel algorithms. When using a pure hardware timer solution, each timed task has its own dedicated hardware timer.

[0003] However, in resource-constrained embedded systems, the number of hardware timers is extremely limited, and the extensive use of hardware timers significantly increases system costs and makes software overly dependent on the hardware platform, resulting in poor portability. Operating system-based software timer schemes traverse linked lists based on system ticks; when the number of timed tasks is large, each interrupt requires traversing the entire linked list, leading to high time complexity and potentially causing excessively long interrupt service function execution times, thus affecting system real-time performance. While traditional time wheel algorithms offer high insertion efficiency, balancing memory usage and accuracy is difficult when handling tasks with mixed long and short time spans. Current timing schemes also lack mechanisms for task state recovery after hardware reset anomalies, posing risks in security-critical scenarios. Software timer schemes using linked list structures require dynamic memory allocation and deallocation at runtime, which can easily lead to memory fragmentation in embedded systems, presenting deterministic risks.

[0004] Therefore, how to provide a timed task management method that consumes few resources and is easy to implement has become an urgent technical problem to be solved. Summary of the Invention

[0005] The main objective of this application is to provide a scheduled task management method, an embedded device, and a computer-readable storage medium, aiming to provide a scheduled task management method with low resource consumption and simple implementation.

[0006] To achieve the above objectives, this application proposes a timed task management method, comprising the following steps: defining a timed task control block structure type, wherein the structure type includes at least a task function pointer, a timed period, a current count value, a task enable flag, a task mode flag, and a task ready flag; Define a structure array variable with a fixed size as a timed task pool, form the structure array variable in the static storage space, and initialize each element in the structure array variable; In the interrupt service routine triggered periodically based on the reference timer, the structure array variable is traversed, and for the timed task whose task enable flag is valid, the current count value of the timed task is decremented. When the current count value decreases to zero, the corresponding task ready flag is set to an active state, and the current count value is reset or the task enable flag is modified according to the task mode flag. In the main loop of the system, the scheduled task is executed. The structure array variable is polled. When the task ready flag of the scheduled task is detected to be in a valid state, the corresponding scheduled task function is called through the task function pointer. After execution, the task ready flag is cleared to zero.

[0007] Preferably, the method further includes the step of providing a task registration interface to dynamically register timed tasks: traversing the structure array variable to find an idle element where the task enable flag is in an invalid state; if the idle element is found, the task function pointer, timer period, and task mode flag of the task to be registered are filled into the idle element; the current count value of the idle element is initialized to the value of the timer period, and the task enable flag is modified to an valid state.

[0008] Preferably, in the interrupt service routine, after the current count value decreases to zero and the task ready flag is set to an active state, the step of resetting the current count value or modifying the task enable flag according to the task mode flag includes: if the task mode flag indicates a periodic mode, then resetting the current count value to the value of the timing period; if the task mode flag indicates a single-time mode, then modifying the task enable flag to an inactive state to stop the subsequent counting of the timed task.

[0009] Preferably, the system further includes a task state recovery step for hardware abnormal reset: during the registration of the timed task, the control block information of the timed task marked as a critical task is written into a backup register or non-volatile memory to generate a task snapshot; when the system experiences an abnormal reset and restarts, the task snapshot is read, and the current count value is reconstructed based on the difference between the abnormal reset time and the current restart time to recover the unfinished critical timed task.

[0010] Preferably, the specific steps for reconstructing the current count value based on the difference between the abnormal reset time and the current restart time include: obtaining the time difference between the system's abnormal reset time and the current restart time, and converting the time difference into a loss count value in units of the interrupt cycle of the reference timer; updating the current count value using formula (1): = - (1); where, This is the current count value after reconstruction. The current count value saved in the task snapshot before the abnormal reset occurred. The calculated loss count value; If the value is less than or equal to zero, the task ready flag of the corresponding scheduled task will be set to the valid state directly after the system restarts.

[0011] Preferably, the structure type further includes a task priority field; the execution of timed task scheduling in the system main loop specifically includes: each time, starting from the highest priority, sequentially checking the task ready flag of each timed task in the structure array variable; when a timed task with a valid task ready flag is found, immediately executing the task function, and after execution, resuming the scan from the highest priority.

[0012] Preferably, the reference timer is the on-chip system tick timer of the microcontroller.

[0013] This application also discloses an embedded device, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement the steps of the timed task management method as described in any of the preceding claims.

[0014] This application also discloses a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the steps of the timed task management method as described in any of the preceding claims.

[0015] The above technical solution has the following advantages: The method provided in this application defines a fixed-size array of structures as a global timed task pool. This approach completely eliminates dynamic memory allocation mechanisms, effectively avoiding memory fragmentation. It significantly reduces the physical resource consumption of read-only memory and random access memory. The method physically isolates the decrementing operation of the timer count from the actual execution logic of the business tasks. The interrupt service routine triggered by the base timer is only responsible for setting the task ready flag to a valid state when the countdown reaches zero. Complex task function calls are delegated to the system's main loop for execution. This architecture greatly shortens the response and execution time of hardware interrupts and prevents system real-time crashes caused by excessively long execution times of single tasks. The method also includes a task state recovery mechanism for hardware abnormal resets. The system updates the current count value according to the formula C1 = C0 - N to recover unfinished critical timed tasks. This method does not rely on the complex kernel of the underlying operating system and can run stably in a bare-metal environment using only standard syntax and basic logic. Attached Figure Description

[0016] The present application will now be described in detail with reference to specific embodiments and accompanying drawings, wherein: Figure 1 The overall flowchart of the timed task management method provided in the embodiments of this application is shown. Detailed Implementation

[0017] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of them. All other embodiments obtained by those skilled in the art based on the embodiments of this application without creative effort are within the scope of protection of this application.

[0018] like Figure 1 As shown, to address the problems of limited hardware timer resources and memory fragmentation and excessively long interrupt service routine execution times caused by operating system-based time wheel algorithms or linked list traversals in existing technologies, Embodiment 1 of this application provides a timed task management method. This method does not rely on any underlying operating system and can effectively reduce the consumption of core system resources, making it particularly suitable for embedded systems such as microcontrollers where both read-only memory and random access memory resources are highly limited. This embodiment will describe in detail the specific execution steps of this management method.

[0019] The first step in this scheduled task management method is the definition of a structure type (S1). Defining a structure type refers to combining multiple data of different types into a single high-level data structure. In this embodiment, the core scheduled task control block structure type includes at least a task function pointer, a timing period, a current count value, a task enable flag, a task mode flag, and a task ready flag. Specifically, the task function pointer directly points to the scheduled task function to be executed, i.e., the entry address of the actual business logic code that the processor needs to call when the timer expires. The timing period precisely sets the execution interval duration of the task. The current count value is used to record the real-time value during the timer's countdown. The task enable flag clearly indicates whether the specific scheduled task is currently authorized and activated by the system. The task mode flag distinguishes whether the task is in a periodic execution mode that needs to be repeatedly triggered or a single-time execution mode that is triggered only once. The task ready flag acts as an asynchronous communication bridge between the underlying hardware interrupt and the upper-layer application scheduling, indicating to the system main loop that the corresponding scheduled task has completed its countdown and fully met the execution conditions. In addition, to ensure the efficiency and reliability of automatically resetting the counter value in periodic mode, this structure type also mandates the inclusion of a counter initial value field, specifically for statically persisting the original initial value of the timing period. As a preferred implementation path, to meet the expansion needs of different application scenarios, this structure type can also include extended fields such as task execution count statistics and callback parameter pointers, thereby further enriching the task context information.

[0020] After completing the type definition, the system proceeds to step S2, the definition and initialization of the structure array variable. In this step, the system needs to define a fixed-size structure array variable as a globally unique pool of timed tasks. In embedded software design architectures with high reliability requirements, frequent dynamic memory allocation and deallocation can easily lead to uncontrollable physical memory fragmentation, severely threatening the stability of long-term uninterrupted operation. This embodiment fundamentally blocks the catastrophic risks of dynamic memory allocation mechanisms by pre-defining a fixed-size structure array variable statically during the compilation phase. The specific physical size of this structure array is configured on demand based entirely on the total number of timed tasks planned for the target product, ensuring that each array element independently and uniquely manages a low-level timed task control block. For example, if a certain type of vehicle control terminal needs to manage a maximum of 8 asynchronous timed tasks in parallel, the array variable is precisely allocated a physical length containing 8 elements. For example, in an embedded system based on an ARM Cortex-M series microcontroller, although on-chip resources are relatively limited (only 4 hardware timers), this fixed-size structure array can uniformly manage the 8 independent timed tasks required by the system. During the initialization phase of system power-on reset, the microcontroller forms the structure array variable in the preset static random access memory space; then, according to step S202, the task function pointer of each element is uniformly initialized to a safe and compliant null pointer; according to step S203, the timing period and initial value of each element are initialized to zero; next, according to step S204, the current count value of each element is initialized to zero; according to step S205, the task enable flag of each element is initialized to an invalid state that prohibits operation; finally, according to step S206, the task mode flag of each element is initialized to the basic default mode. At this point, the entire global timed task pool is safely reset to a completely clean, absolutely certain, and predictable zero initial state.

[0021] The core driving force of the system operation comes from the timer counting implementation stage in step S3. The foundation of this stage relies on a hardware interrupt service routine based on the periodic and stable triggering of a reference timer. The reference timer preferably uses the on-chip system tick timer peripheral module integrated within the microcontroller, which is hardware-configured to generate a high-precision timing interrupt signal with absolute periodicity; for example, the trigger clock cycle for each interrupt is precisely set to 1ms. Whenever the 1ms hardware clock clock signal arrives, the kernel processor is forcibly interrupted from its currently running thread and quickly switches to the timing interrupt service routine with the highest scheduling authority. Within this extremely short and precious interrupt context, the program uses compact loop instructions to traverse the statically defined structure array variables. To minimize interrupt time, the system only intervenes in active timed tasks whose task enable flag is currently active, unconditionally decrementing their corresponding current count value by one. When the logic checker detects that the current count value of an active timed task has strictly decremented to zero, the processor immediately sets the corresponding task ready flag to the trigger-enabled state. Next, the system performs intelligent branching based on the task mode flag built into the independent task to decide whether to reload the current count value or completely modify the task enable flag. In specific scenarios, if the task mode flag explicitly indicates that the task belongs to periodic mode, the program automatically resets the current count value to a fixed value for the timing period, thus seamlessly and automatically starting the next new countdown lifecycle. Conversely, if the task mode flag indicates that the task belongs to single-time mode, the program immediately overwrites and modifies the task enable flag to an invalid state, directly intercepting and terminating any subsequent meaningless counting polling behavior for that specific timed task. Through this ingenious logic stripping architecture, the number of machine instructions inside the interrupt service routine is strictly limited and the execution time is highly deterministic, completely eliminating the risk of timing collapse caused by traversing complex dynamic linked lists or directly executing time-consuming business logic code in the interrupt. This is beneficial to improving the stability of the 1ms baseline hardware tick and the real-time response capability of the microcontroller.

[0022] The final execution of the business logic culminates in step S4, the task execution phase upon timed expiration. This step, architecturally designed to operate entirely outside the stringent hardware interrupt context, is cleverly and independently placed within the lowest-priority background iterative process of the system's main loop. During each complete iteration of the main loop, the system's top-level task scheduler continuously and sequentially probes the structure array variables. When the scheduler detects that the task readiness flag for a given timed task is currently lit and valid, it indicates that the countdown period for that application task has been successfully completed. At this point, the scheduler immediately follows the trail, using the pre-bound task function pointer, to call the corresponding target timed task function, causing the CPU to execute complex business logic code at full speed, such as physical button debounce scanning or external sensor analog-to-digital conversion. After all the specific business logic code has been successfully executed, the scheduler performs the cleanup, immediately resetting the task readiness flag to zero, allowing the entire task control block to smoothly transition and return to a suspended state, silently awaiting the next countdown hardware interrupt trigger. This application's embodiments innovatively separate the physical and logical execution of the interrupt-level rapid flag setting from the asynchronous execution of the application-layer main loop. This not only fundamentally resolves the fatal risk of stack overflow caused by the stacked execution of massive complex tasks within a single hardware interrupt, but also significantly reduces the instantaneous peak occupancy of the central processing unit, improving cross-platform applicability. Under the unified scheduling guarantee of the main loop, various specific application tasks can be executed precisely in parallel. For example, key scanning (set to a period of 10ms, periodic mode), LED blinking control (set to a period of 500ms, periodic mode), sensor data acquisition (set to a period of 100ms, periodic mode), and communication timeout detection (set to a period of 1s, i.e., 1000ms, single-time mode) operate independently and systematically.

[0023] Based on the framework of Embodiment 1 above, Embodiment 2 of this application further provides a timed task management method that includes a dynamic task registration interface and a highly reliable state recovery mechanism to cope with more complex industrial application scenarios.

[0024] In practical engineering development, some application scenarios do not require static registration of all scheduled tasks during system initialization. Instead, it is desirable to dynamically add new scheduled tasks based on trigger conditions during business operation. Therefore, this embodiment provides a task registration interface on top of the structure array variable to implement the dynamic registration of scheduled tasks. Specifically, when the upper-layer application calls this task registration interface, the microcontroller iterates through the structure array variable, searching for free elements whose task enable flags are currently invalid. This design cleverly reuses the allocated static memory pool, completely avoiding dynamic memory allocation operations. If a free element is successfully found during the iteration, the microcontroller fills the task function pointer, timing period, and task mode flag of the task to be registered into the data structure of that free element. Subsequently, the microcontroller initializes the current count value of the free element to the value of the passed timing period and modifies the corresponding task enable flag to an effective state. Through this series of operations, the system provides the upper-layer business layer with great scheduling flexibility without increasing additional storage overhead, allowing dynamic tasks such as sensor timed polling or communication timeout retransmission to be created at any time and included in the underlying unified interrupt count queue of the base timer.

[0025] Furthermore, in safety-critical scenarios such as connected vehicles, electronic control units are highly susceptible to power fluctuations or strong electromagnetic interference, which can trigger hardware watchdog resets or abnormal kernel restarts. Traditional timing management schemes lose all timer states stored in volatile random access memory after a system reset, leading to fatal interruptions in critical business processes such as motor control sequences. To address this common industry challenge, this embodiment innovatively adds a task state recovery step for hardware resets. During dynamic registration or static initialization of critical timing tasks, the system writes the core information of the control block of the timer task marked as critical into a separate backup register or external non-volatile memory in real time. This core information includes the task identifier, timing period, current count value, task enable flag, and task snapshot time, thus generating a task snapshot. When the microcontroller experiences a reset and restarts, its underlying bootloader actively checks the reset status register during the system core initialization phase. Once it identifies that the startup is a reset wake-up, the bootloader immediately reads the task snapshot data stored in the backup register or non-volatile memory. Subsequently, the system will obtain the time difference between the task snapshot time and the current restart time, and convert this absolute time difference into a loss count value in units of the interrupt cycle of the base timer. After obtaining the above parameters, The system strictly uses formulas = - This updates the current damaged count value. In this formula, The calculated current count value after reconstruction. The current count value saved in the task snapshot before the abnormal reset occurred. This represents the calculated loss count value. Further, the system performs a logical check on the reconstructed current count value. If the calculated... If the calculated value is greater than zero, it is written back to the structure array variable to continue the countdown. If the value is less than or equal to zero, it indicates that the scheduled task should have expired within the hardware crash recovery time blind zone. In this case, the system will directly force the task ready flag of the corresponding scheduled task to be valid after restarting. Through this hardware-software collaborative breakpoint resumption mechanism, this embodiment improves the fault tolerance and robustness of embedded devices.

[0026] To further improve the system's deterministic response to critical tasks, Embodiment 3 of this application introduces a task priority scheduling mechanism based on Embodiments 1 and 2. In extreme cases of multi-task concurrency, multiple timed tasks may simultaneously count down to zero within the interrupt tick of the same base timer, at which point multiple task readiness flags are simultaneously set to a valid state. In the traditional polling architecture, the execution order of tasks depends entirely on their physical storage index order in the structure array variable, which obviously cannot meet the differentiated processing requirements of real-time systems for task urgency. Therefore, this embodiment expands the fields of the structure type by adding a task priority field, which is used to clearly identify the urgency scheduling weight of each timed task with a quantified value. Correspondingly, the core architecture of the step of scheduling timed tasks that have expired in the system's main loop has also been upgraded. Specifically, the main loop scheduler no longer performs a simple linear traversal, but instead checks the task readiness flag of each timed task in the structure array variable sequentially, starting from the highest priority. When the scheduler scans from high to low and finds the first timed task with a valid task readiness flag, the processor immediately jumps to execute the task function via a pointer. Most importantly, after the single task function completes execution, the scheduler forcibly interrupts the current scan memory, jumps back, and starts a new round of global scanning from the highest priority. This preemptive main loop scheduling strategy produces excellent technical results: as long as a high-priority task, such as chassis communication data packet parsing, reaches the ready state, it will definitely be acquired and executed by the central processing unit before low-priority tasks, such as screen user interface refresh tasks. This effectively prevents low-priority time-consuming tasks from blocking the scheduling of high-priority urgent tasks, and achieves strict priority scheduling characteristics in a bare-metal system with extremely low code and storage overhead without introducing a large and complex real-time operating system kernel.

[0027] Based on the technical solutions of the above embodiments, this application exhibits the following five significant advantages at the system overall level: First, extremely low resource consumption, managed through a single fixed structure array, eliminating the need for dynamic allocation, effectively avoiding memory fragmentation, and minimizing ROM and RAM usage; Second, simple and convenient implementation, completely decoupling from the underlying operating system, allowing independent operation in a bare-metal environment; Third, excellent portability, with the core implementation relying on standard C language syntax, allowing seamless cross-platform portability by adapting to the base timer; Fourth, flexible task configuration, supporting not only dynamic registration but also independent configuration of running modes and priorities for individual tasks; Fifth, stable timing accuracy, thanks to the highly separated "interrupt flag setting, main loop execution" mode, accurately ensuring the system's real-time response capability.

[0028] It will be apparent to those skilled in the art that this application is not limited to the details of the exemplary embodiments described above, and that this application can be implemented in other specific forms without departing from the spirit or essential characteristics of this application. Therefore, the embodiments should be considered illustrative and non-limiting in all respects, and the scope of this application is defined by the appended claims rather than the foregoing description. Thus, all variations falling within the meaning and scope of equivalents of the claims are intended to be included within this application. No reference numerals in the claims should be construed as limiting the scope of the claims. All content not described in detail in the specification is prior art known to those skilled in the art.

Claims

1. A method for managing scheduled tasks, characterized in that, Includes the following steps: Define a timed task control block structure type, wherein the structure type includes at least a task function pointer, a timer period, a current count value, a task enable flag, a task mode flag, and a task ready flag; Define a structure array variable with a fixed size as a timed task pool, form the structure array variable in the static storage space, and initialize each element in the structure array variable; In the interrupt service routine triggered periodically based on the reference timer, the structure array variable is traversed, and for the timed task whose task enable flag is valid, the current count value of the timed task is decremented. When the current count value decreases to zero, the corresponding task ready flag is set to an active state, and the current count value is reset or the task enable flag is modified according to the task mode flag. In the main loop of the system, the scheduled task is executed. The structure array variable is polled. When the task ready flag of the scheduled task is detected to be in a valid state, the corresponding scheduled task function is called through the task function pointer. After execution, the task ready flag is cleared to zero.

2. The scheduled task management method according to claim 1, characterized in that, It also includes the step of providing a task registration interface to dynamically register timed tasks: traversing the structure array variable to find a free element where the task enable flag is invalid; if the free element is found, the task function pointer, timer period, and task mode flag of the task to be registered are filled into the free element. The current count value of the idle element is initialized to the value of the timing period, and the task enable flag is modified to be active.

3. The scheduled task management method according to claim 1, characterized in that, In the interrupt service routine, after the current count value decreases to zero and the task ready flag is set to an active state, the step of resetting the current count value or modifying the task enable flag according to the task mode flag includes: if the task mode flag indicates a periodic mode, then resetting the current count value to the value of the timing period; if the task mode flag indicates a single-time mode, then modifying the task enable flag to an inactive state to stop the subsequent counting of the timed task.

4. The scheduled task management method according to claim 1, characterized in that, It also includes a task state recovery step for hardware abnormal reset: when the timed task is registered, the control block information of the timed task marked as a critical task and the task snapshot time are written into the backup register or non-volatile memory to generate a task snapshot. When the system experiences an abnormal reset and restarts, the task snapshot is read, and the current count value is reconstructed based on the difference between the abnormal reset time and the current restart time to recover the unfinished critical timed tasks.

5. The scheduled task management method according to claim 4, characterized in that, The specific steps for reconstructing the current count value based on the difference between the abnormal reset time and the current restart time include: obtaining the time difference between the task snapshot time and the current restart time, and converting the time difference into a lost count value in units of the interrupt cycle of the base timer; updating the current count value using formula (1): = - (1); where, This is the current count value after reconstruction. The current count value saved in the task snapshot before the abnormal reset occurred. The calculated loss count value; If the value is less than or equal to zero, the task ready flag of the corresponding scheduled task will be set to the valid state directly after the system restarts.

6. The scheduled task management method according to claim 1, characterized in that, The structure type also includes a task priority field, which is used to indicate the priority order of the timed tasks; the execution of timed task scheduling in the system main loop specifically includes: checking the task ready flag of each timed task in the structure array variable in descending order of priority represented by the task priority field; when a timed task with a valid task ready flag is found, the task function is executed immediately, and after execution, the scan starts again from the highest priority.

7. The scheduled task management method according to claim 1, characterized in that, The reference timer is the on-chip system tick timer of the microcontroller.

8. An embedded device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the computer program, it implements the steps of the timed task management method as described in any one of claims 1 to 7.

9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the steps of the timed task management method as described in any one of claims 1 to 7.