An application startup task scheduling method and related device
Patent Information
- Application Number
- CN202610451241.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-04-08
- Publication Date
- 2026-08-18
AI Technical Summary
[0003]集中顺序初始化方式实现简单,但会导致主线程被长时间占用,从而延长应用启动时间,并且SDK之间的执行顺序依赖人工维护,容易在版本迭代过程中引发时序错误,且不利于模块解耦与扩展
[0018] In summary, this invention introduces a dual-drive mechanism combining milestone gating and RunLoop idle frame scheduling, transforming SDK initialization from traditional sequential or fixed-delay execution to an adaptive scheduling method based on business semantics. By distributing non-critical tasks across idle frames for gradual execution, the initial screen rendering time is effectively shortened. Milestone constraints enable structured management of task timing, avoiding the risks associated with manual order maintenance. Binding execution timing to business states improves scheduling accuracy and environmental adaptability. Furthermore, the adoption of a single-frame, single-task strategy ensures a smooth and seamless user interaction process, and a unified registration mechanism enables low-intrusion expansion, enhancing system maintainability and scalability.
Smart Images

Figure CN122593918A_ABST
Abstract
Description
Technical Field
[0001] This specification relates to the field of mobile application startup performance optimization technology, and more specifically, this application relates to an application startup task scheduling method and related devices. Background Technology
[0002] As mobile applications continue to grow in scale, they typically need to initialize multiple SDK modules during the cold start phase, such as logging systems, network components, statistical analysis, security modules, and multimedia services. Existing technologies commonly employ three initialization methods: centralized sequential initialization, fixed-time delayed execution, and asynchronous initialization via sub-threads.
[0003] While centralized sequential initialization is simple to implement, it can lead to the main thread being occupied for a long time, thus extending the application startup time. Furthermore, the execution order between SDKs depends on manual maintenance, which can easily cause timing errors during version iterations and is not conducive to module decoupling and expansion.
[0004] The fixed-time delay method postpones part of the SDK initialization through mechanisms such as dispatch_after to reduce the pressure during the startup phase. However, this method relies on fixed time constants and cannot be accurately matched with the actual business state (such as the completion of interface rendering), which can easily lead to problems such as unreasonable execution timing or functional delays.
[0005] The asynchronous initialization method in child threads attempts to improve execution efficiency through multithreading. However, since some SDKs must be executed on the main thread, this method has compatibility and thread safety issues, and it is also difficult to guarantee the execution order between SDKs, thus increasing system complexity.
[0006] Therefore, the relevant technologies still have problems in terms of startup performance optimization and task scheduling, such as uncontrollable execution timing, concentrated pressure on the main thread, and difficulty in managing task dependencies, which need to be further improved. Summary of the Invention
[0007] The summary section introduces a series of simplified concepts, which will be further explained in detail in the detailed description section. This summary section is not intended to limit the key and essential technical features of the claimed technical solution, nor is it intended to determine the scope of protection of the claimed technical solution.
[0008] Firstly, this application proposes an application startup task scheduling method, including: After the application starts, a startup event manager is created, and the current milestone state and ordered wait queue are initialized. Receive startup tasks registered by each business module and configure a deadline milestone for each startup task. The enumerated time node identifier associated with the startup task is used to characterize the latest execution time boundary of the startup task. The value of the deadline milestone corresponds one-to-one with the system's predefined milestone sequence. Based on the aforementioned deadline milestones, the aforementioned startup tasks are sorted and inserted to construct an ordered waiting queue arranged in ascending order of the deadline milestones; During the application lifecycle, advance the current milestone and trigger the first scheduling path based on the current milestone to execute the startup task that meets the above deadline milestone; During the idle frame of the main thread RunLoop, the second scheduling path is triggered to perform idle scheduling and execution of the startup tasks in the above ordered waiting queue. By coordinating the first and second scheduling paths mentioned above, the startup task can be executed in stages during critical lifecycle nodes and idle frames.
[0009] In one feasible implementation, the above-mentioned receiving of startup tasks registered by each business module and configuring a deadline milestone for each startup task includes: When a task registration request is received, the current milestone status mentioned above is read. If the current milestone status is greater than or equal to the aforementioned deadline milestone, execute the aforementioned startup task immediately. When the current milestone status is less than the aforementioned deadline milestone, construct a task node that includes task execution logic and the deadline milestone.
[0010] In one feasible implementation, the above-mentioned sorting and insertion of the startup tasks based on the deadline milestones to construct an ordered waiting queue arranged in ascending order of the deadline milestones includes: Traverse the ordered waiting queue above and find the position of the first deadline milestone that is greater than the current task's deadline milestone; Insert the above task nodes into the corresponding positions; If no suitable location is found, add the aforementioned task node to the end of the queue. This ensures that the aforementioned orderly waiting queue is always arranged in ascending order according to the deadline milestone.
[0011] In one feasible implementation, advancing the current milestone and triggering the first scheduling path includes: Receive milestone advancement instructions and update the current milestone to a new milestone value, wherein the new milestone value is only allowed to increase monotonically; Traverse the ordered waiting queue above, starting from the head of the queue, and check the deadline milestones of the task nodes one by one; Dequeue and execute task nodes whose deadline milestones are less than or equal to the current milestone in sequence; The traversal terminates when a task node with a cutoff milestone greater than the current milestone is encountered.
[0012] In one feasible implementation, the above-mentioned triggering of the second scheduling path during the main thread RunLoop idle frame to perform idle scheduling execution on the aforementioned ordered waiting queue includes: Idle scheduling is triggered during the kCFRunLoopBeforeWaiting phase of the main thread's RunLoop. When the above ordered waiting queue includes task nodes, read the task node at the head of the queue; When the deadline of the above task node is less than the preset Future milestone, the above task node is executed in the current idle frame, wherein only one task node is executed in each idle frame.
[0013] In one feasible implementation, it further includes: When the deadline milestone of the above task node is equal to the above preset Future milestone, determine whether the current milestone has reached the preset completion milestone on the interface; When the current milestone is greater than or equal to the milestone completed on the above interface, the above task node will be removed from the above ordered waiting queue and the corresponding task will be executed. If the current milestone is less than the milestone completed on the above interface, keep the above task node in the above ordered waiting queue, and repeat the judgment in subsequent idle frames.
[0014] In one feasible implementation, it further includes: During the execution of the first scheduling path and the second scheduling path, a mutual exclusion flag is used to control that the two paths are not executed simultaneously. The execution of the second scheduling path is prohibited when the first scheduling path is executed. If the execution of the first scheduling path is detected while the second scheduling path is being executed, it will return directly. After all startup tasks have completed, keep the idle scheduler returning quickly and remove the RunLoop observer when releasing resources.
[0015] Secondly, the present invention also proposes an application startup task scheduling system for implementing the application startup task scheduling method according to any one of the first aspects of the claims, comprising: The creation unit is used to create a startup event manager after the application starts, and to initialize the current milestone state and the ordered wait queue; The configuration unit is used to receive the startup tasks registered by each business module and configure a deadline milestone for each startup task. The enumerated time node identifier associated with the startup task is used to characterize the latest execution time boundary of the startup task. The value of the deadline milestone corresponds one-to-one with the system's predefined milestone sequence. The building unit is used to sort and insert the above-mentioned startup tasks based on the above-mentioned deadline milestones to build an ordered waiting queue arranged in ascending order of the deadline milestones; The first scheduling unit is used to advance the current milestone during the application lifecycle and trigger the first scheduling path based on the current milestone to execute the startup task that meets the above deadline milestone. The second scheduling unit is used to trigger the second scheduling path during the idle frame of the main thread RunLoop to perform idle scheduling execution of the startup tasks in the above-mentioned ordered waiting queue. The execution unit is used to coordinate scheduling through the first scheduling path and the second scheduling path to realize the phased execution of the startup task at key nodes in the life cycle and during idle frames.
[0016] Thirdly, the present invention also proposes an electronic device comprising: a memory and a processor, characterized in that the processor, when executing a computer program stored in the memory, implements the steps of the application startup task scheduling method as described in any of the first aspects.
[0017] Fourthly, the present invention also provides a computer-readable storage medium having a computer program stored thereon, characterized in that, when the computer program is executed by a processor, it implements the steps of the application startup task scheduling method as described in any of the first aspects.
[0018] In summary, this invention introduces a dual-drive mechanism combining milestone gating and RunLoop idle frame scheduling, transforming SDK initialization from traditional sequential or fixed-delay execution to an adaptive scheduling method based on business semantics. By distributing non-critical tasks across idle frames for gradual execution, the initial screen rendering time is effectively shortened. Milestone constraints enable structured management of task timing, avoiding the risks associated with manual order maintenance. Binding execution timing to business states improves scheduling accuracy and environmental adaptability. Furthermore, the adoption of a single-frame, single-task strategy ensures a smooth and seamless user interaction process, and a unified registration mechanism enables low-intrusion expansion, enhancing system maintainability and scalability.
[0019] Other advantages, objectives and features of this application will be apparent in part from the description which follows, and in part from what those skilled in the art will understand through study and practice of this application. Attached Figure Description
[0020] Various other advantages and benefits will become apparent to those skilled in the art upon reading the following detailed description of preferred embodiments. The accompanying drawings are for illustrative purposes only and are not intended to limit this specification. Furthermore, the same reference numerals denote the same parts throughout the drawings. In the drawings: Figure 1 This application provides a schematic flowchart of an application startup task scheduling method. Figure 2 This application provides a schematic diagram of the overall architecture of an application startup task scheduling system. Figure 3 A schematic diagram of a task scheduling timeline provided in this application embodiment; Figure 4 This application provides a schematic diagram of a task registration process. Figure 5 This application provides a schematic diagram of an idle frame scheduling decision-making process. Figure 6 A structural schematic diagram of an application startup task scheduling system provided in this application embodiment; Figure 7 This is a schematic diagram of an electronic device structure provided in an embodiment of this application. Detailed Implementation
[0021] The terms "first," "second," "third," "fourth," etc. (if present) in the specification, claims, and accompanying drawings of this application are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments described herein can be implemented in a sequence other than that illustrated or described herein. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus. The technical solutions of the embodiments of this application will now be clearly and completely described in conjunction with the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of them.
[0022] Please see Figure 1 This is a flowchart illustrating an application startup task scheduling method provided in an embodiment of this application, which may specifically include: S110. After the application starts, create a startup event manager and initialize the current milestone state and the ordered wait queue; S120. Receive the startup tasks registered by each business module and configure a deadline milestone for each startup task. The enumerated time node identifier associated with the startup task is used to characterize the latest execution time boundary of the startup task. The value of the deadline milestone corresponds one-to-one with the system's predefined milestone sequence. S130. Based on the aforementioned deadline milestones, sort and insert the aforementioned startup tasks to construct an ordered waiting queue arranged in ascending order of the deadline milestones. S140. Advance the current milestone during the application lifecycle and trigger the first scheduling path based on the current milestone to execute the startup task that meets the above deadline milestone. S150. Trigger the second scheduling path during the idle frame of the main thread RunLoop to perform idle scheduling execution on the startup tasks in the above-mentioned ordered waiting queue. S160. Through the coordinated scheduling of the first scheduling path and the second scheduling path, the startup task is executed in stages during key lifecycle nodes and idle frames.
[0023] For example, such as Figure 1 , Figure 2 and Figure 3 As shown, during the application startup phase, the system first initializes the startup event manager by the main thread after the application process is created. In step S110, a globally unique startup event manager instance is constructed to initialize the current milestone state and create an empty ordered waiting queue for subsequent unified management of the startup tasks of each business module.
[0024] In step S120, each business module can call the unified interface to register a startup task at any time. During the registration process, a corresponding deadline milestone is bound to each startup task. This deadline milestone comes from a predefined monotonically increasing milestone enumeration sequence, which is used to clearly constrain the latest execution time of the task. When it is detected during registration that the current milestone has reached or exceeded the deadline milestone, the corresponding task is executed directly, thereby ensuring that no task is missed.
[0025] In step S130, for tasks that have not yet reached their deadline milestones, the system encapsulates them into task nodes that include task execution logic and deadline milestones, and inserts them sequentially based on the deadline milestones. By traversing the current ordered waiting queue, the system finds the position where the first deadline milestone is greater than the new task and inserts it. If the new task does not exist, it is appended to the end of the queue, thereby always maintaining the queue in ascending order of deadline milestones, providing a foundation for efficient scheduling in the future.
[0026] In step S140, as the application lifecycle progresses, the business code actively calls the milestone advancement interface at key nodes to update the current milestone value and triggers the first scheduling path (such as...). Figure 2 In path A), the system sequentially traverses the ordered waiting queue starting from the head of the queue, dequeuing all tasks whose deadline milestones are less than or equal to the current milestone and executing them synchronously until a task that does not meet the conditions is encountered, at which point the traversal stops. This ensures the correctness of the execution sequence while keeping the traversal complexity within a range related to the number of tasks being executed.
[0027] In step S150, when the main thread RunLoop enters the idle frame phase, the system triggers the second scheduling path (e.g., ...) through the observer registered in the kCFRunLoopBeforeWaiting event. Figure 2 In path B), the system first checks whether the first scheduling path is being executed to avoid concurrent conflicts. If there are no conflicts and the waiting queue is not empty, only the task node at the head of the queue is retrieved for processing. When the deadline milestone of the task is less than the preset Future milestone, it can be executed in advance in the current idle frame without waiting for the milestone to be reached, thus utilizing the gap between frames to digest non-critical tasks. When the deadline milestone of the task is equal to the Future milestone, it is necessary to further determine whether the current milestone has reached the milestone corresponding to the completion of the interface display. Execution is only performed when the condition is met; otherwise, the current frame is skipped and the judgment continues in the subsequent idle frame, thus ensuring that the critical user interface process is not affected, while realizing the orderly execution of delayed tasks.
[0028] In step S160, through the synergistic effect of the first scheduling path and the second scheduling path, on the one hand, the milestone-driven mechanism is used to ensure that the critical tasks are completed before the specified time node, and on the other hand, the idle frame scheduling mechanism is used to distribute the execution of some tasks in advance or postponed, thereby effectively reducing the instantaneous load of the main thread, avoiding performance jitter in the startup phase, and finally realizing the phased and smooth execution of startup tasks in the critical nodes of the life cycle and the idle time window, improving the application startup efficiency and user interface response performance.
[0029] like Figure 3As shown, the execution distribution of various tasks on the main thread timeline during the startup process is explained to verify the effectiveness of the milestone-driven and RunLoop idle frame collaborative scheduling mechanism. Taking the application cold start process as an example, the startup phase is divided from the perspective of the main thread, and multiple key milestone nodes are set sequentially on the timeline, including the startup start milestone LaunchBegin, the UI construction start milestone UIBegin, the startup process end milestone LaunchEnd, and the UI completion milestone UIEnd. Each milestone is actively triggered by the corresponding business module during operation by calling the milestone advancement interface, thereby driving the first scheduling path to batch schedule and execute tasks.
[0030] In the aforementioned timeline, startup tasks are categorized into critical tasks, secondary tasks, homepage rendering tasks, and Future tasks based on business importance. Critical tasks, including logging system initialization, crash monitoring initialization, and basic configuration loading, typically have their deadline milestones set to LaunchBegin or LaunchEnd. These tasks are prioritized for execution via the first scheduling path during milestone progression, ensuring that the application's basic capabilities are initialized early in the startup process.
[0031] For secondary tasks, including network pre-connection, non-core SDK initialization, and some data preparation operations, their deadline milestones can be set before LaunchEnd or UIEnd. In this embodiment, in addition to being triggered during milestone progression, these tasks can also be executed gradually during the main thread's RunLoop idle frames via a second scheduling path. Specifically, tasks are executed in batches during multiple frame gaps, thereby splitting the originally concentrated initialization operations into multiple time segments and reducing the instantaneous load on the main thread.
[0032] For the homepage rendering task, its execution mainly focuses on the period from UIBegin to UIEnd, which corresponds to the critical path of interface construction and drawing. To ensure smooth interface rendering, this embodiment prioritizes the execution of rendering-related tasks in this stage and avoids non-critical tasks occupying main thread resources through delayed scheduling or distributed execution strategies.
[0033] For Future tasks, including data reporting, statistical analysis initialization, and some delayed SDK loading, their deadline milestones are uniformly set as Future milestones, and gating is performed through a second scheduling path. Specifically, the system only allows such tasks to be removed from the ordered waiting queue and executed when the current milestone reaches or exceeds UIEnd, thus ensuring that their execution does not affect the initial screen display process.
[0034] Through the above implementation method, a hierarchical and ordered task execution structure can be formed on the main thread timeline: critical tasks are completed centrally at the beginning of startup, secondary tasks are executed in a distributed manner during the inter-frame gaps, and Future tasks are executed after the interface is completed. This scheduling method effectively avoids the main thread blocking problem caused by the concentrated execution of tasks during traditional startup, and coordinates the task execution process with the interface rendering rhythm, thereby improving application startup performance and user experience.
[0035] In one feasible implementation, the above-mentioned receiving of startup tasks registered by each business module and configuring a deadline milestone for each startup task includes: When a task registration request is received, the current milestone status mentioned above is read. If the current milestone status is greater than or equal to the aforementioned deadline milestone, execute the aforementioned startup task immediately. When the current milestone status is less than the aforementioned deadline milestone, construct a task node that includes task execution logic and the deadline milestone.
[0036] For example, when various business modules register to start tasks through a unified interface, the task registration process is implemented through the interface provided by the startup event manager. The specific interface format is as follows: - (void)act:(dispatch_block_t)action beforeEvent:(DYLaunchEvent)event; The "action" refers to the initialization task logic that needs to be executed on the main thread, and the "event" is the deadline milestone, corresponding to the predefined milestone enumeration type DYLaunchEvent, whose value is used to limit the latest lifecycle node for task execution. Each business module can call this interface at any location to complete task registration; for example, the player module can register an initialization task before the homepage is displayed. [[DYLaunchEventManager sharedManager] act:^{ [DYPlayerSDK setup]; } beforeEvent:DYLaunchEventUIEnd]; When the aforementioned interface is invoked, the system first reads the currently maintained milestone status variable `_event`. This variable represents the current lifecycle stage of the application startup and is continuously updated during subsequent scheduling. Then, the system compares the current milestone status with the stated deadline milestone.
[0037] When it is detected that _event >= event, it indicates that the current system state has reached or exceeded the latest execution time of this task. At this time, the system no longer queues and schedules this task, but directly synchronously executes the task logic corresponding to the action in the main thread, that is, directly calls the block and returns. Through this processing method, the task can still be guaranteed to be executed even when the task registration is lagged, thus avoiding the problem of function loss caused by scheduling delay.
[0038] When it is detected that _event < event, it indicates that this task is still within the schedulable range. At this time, the system encapsulates the task into a task node object. The task node includes the task execution logic actionBlock and the corresponding deadline milestone, which can be represented in the data structure form of {actionBlock, deadline}. This task node is then incorporated into the unified scheduling management system.
[0039] After the task node is constructed, the system performs an ordered insertion process on the task based on the deadline milestone. Specifically, by sequentially traversing the current ordered waiting queue, find the first position idx that satisfies its deadline value being greater than the deadline of the current task; when such a position exists, insert the current task node at this position; when there is no position that meets the condition, append the task node to the end of the queue. Through the above insertion strategy, the entire waiting queue is always sorted in ascending order according to the deadline value.
[0040] Since the queue is maintained in an ordered manner during the task registration phase, in the subsequent scheduling process, no additional sorting operation is required. Only by sequentially reading from the head of the queue can the task that needs to be executed earliest be obtained, thus providing efficient data support for batch execution based on milestone advancement and frame-by-frame execution based on RunLoop idle frames.
[0041] Through the above implementation methods that combine interface calls, status judgment, task encapsulation, and ordered insertion, this embodiment completes the determination and classification processing of the task execution time during the task registration phase. On the one hand, it ensures the reliable execution of overdue tasks through the immediate execution mechanism. On the other hand, by constructing structured task nodes and ordered queues, it provides a unified data basis for subsequent phased scheduling, thereby improving the overall scheduling efficiency and execution stability of the system.
[0042] It should be noted that the above milestones are used to discretize the key lifecycle stages in the application startup process and establish a one-to-one correspondence between enumeration values and specific triggering times, thereby providing a unified time benchmark for scheduling startup tasks. As shown in Table 1, LaunchBegin corresponds to the initial stage of application startup, with an enumeration value of 1, and is initiated when the application delegate method application:didFinishLaunchingWithOptions: begins execution. This stage marks the formal start of the application startup process and is suitable for executing the earliest critical tasks such as log initialization and basic configuration loading. UIBegin corresponds to the initial stage of interface construction, with an enumeration value of 2, and is initiated before the loadView method of the home page ViewController begins execution. This stage marks the imminent start of the interface rendering process and is suitable for executing initialization tasks related to interface preparation. LaunchEnd corresponds to the end stage of the startup process, with an enumeration value of 3, and is initiated when the application:didFinishLaunchingWithOptions: method is about to return. This stage indicates that the basic application startup process is basically completed and can be used to trigger the final execution of tasks up to the startup stage. UIEnd corresponds to the completion stage of the interface display, with an enumeration value of 4. It is advanced when the viewDidAppear: method of the homepage ViewController completes execution. This stage marks the completion of the rendering and display of the first screen interface and is an important dividing point distinguishing critical startup stages from subsequent delayed tasks. Future corresponds to the delayed execution flag, with an enumeration value of 5. It does not correspond to a specific automatic advancement time, but rather serves as a logical flag to identify task types that are only allowed to be executed after the interface is completed, thereby enabling delayed scheduling control of non-critical tasks. Through the above milestone definition and advancement mechanism, the different stages in the application startup process can be standardized and a clear and controllable timing basis can be provided for subsequent milestone-based task scheduling.
[0043] Table 1
[0044] In one feasible implementation, the above-mentioned sorting and insertion of the startup tasks based on the deadline milestones to construct an ordered waiting queue arranged in ascending order of the deadline milestones includes: Traverse the ordered waiting queue above and find the position of the first deadline milestone that is greater than the current task's deadline milestone; Insert the above task nodes into the corresponding positions; If no suitable location is found, add the aforementioned task node to the end of the queue. This ensures that the aforementioned orderly waiting queue is always arranged in ascending order according to the deadline milestone.
[0045] For example, in this embodiment, after the system completes the registration of the startup task and constructs the corresponding task node, it does not use a full sort or additional sorting algorithm to uniformly sort all tasks. Instead, it directly completes the ordered maintenance based on the deadline milestone during the insertion phase. Specifically, each task node contains the task execution logic actionBlock and the corresponding deadline milestone. The system compares the deadline value to achieve the ordered organization of tasks in the queue.
[0046] like Figure 4 As shown, during the insertion process, the system performs a sequential traversal of the existing ordered waiting queue, comparing the deadline values of each task node sequentially starting from the head of the queue. When the system finds the first position where the deadline milestone is greater than that of the task to be inserted, the insertion position idx is determined. Subsequently, the current task node is inserted into this position, placing it after all tasks with smaller deadline milestones and before tasks with larger deadline milestones, thus ensuring the local order of the queue.
[0047] If no position meeting the conditions is found during the traversal, it means that the deadline milestone value of the task to be inserted is greater than or equal to the deadline milestone values of all existing tasks in the queue. In this case, the system directly appends the task node to the end of the queue. Through the combination of the above two insertion strategies, all tasks are arranged in an ordered manner when they enter the queue.
[0048] Furthermore, since the ordered waiting queue is always arranged in ascending order according to the deadline milestones, the highest priority task node can be directly obtained from the head of the queue without additional sorting during subsequent scheduling. For example, in the scheduling process triggered by milestone advancement, it is only necessary to read sequentially from the head of the queue and determine whether the deadline milestone meets the execution conditions. Once the first task that does not meet the conditions is encountered, the traversal can be stopped, thereby avoiding a full scan of the entire queue. Similarly, in the scheduling process based on RunLoop idle frames, it is only necessary to read the task at the head of the queue to complete frame-by-frame scheduling and execution.
[0049] By adopting the "insertion-as-sort" queue maintenance method described above, this embodiment significantly reduces the time complexity of the scheduling process while ensuring the correctness of the task execution order. The complexity of the task dequeue operation is reduced from depending on the total length of the queue to being related to the actual number of tasks executed, thereby improving the overall scheduling efficiency in multi-task scenarios and providing efficient data structure support for the subsequent dual-path scheduling mechanism.
[0050] In one feasible implementation, advancing the current milestone and triggering the first scheduling path includes: Receive milestone advancement instructions and update the current milestone to a new milestone value, wherein the new milestone value is only allowed to increase monotonically; Traverse the ordered waiting queue above, starting from the head of the queue, and check the deadline milestones of the task nodes one by one; Dequeue and execute task nodes whose deadline milestones are less than or equal to the current milestone in sequence; The traversal terminates when a task node with a cutoff milestone greater than the current milestone is encountered.
[0051] For example, in this embodiment, the first scheduling path is triggered based on a milestone advancement mechanism in the application lifecycle, used to centrally schedule and execute startup tasks that meet the execution conditions at key time nodes. Specifically, when the application reaches a certain lifecycle stage, the business code actively calls the following interface to advance the milestone: - (void)setEvent:(DYLaunchEvent)event; After the interface is invoked, the system first receives the milestone advancement instruction and updates the current milestone status variable _event to the new milestone value. To ensure the correctness and consistency of task execution timing, the milestone update process only allows monotonically increasing values, meaning the new milestone value must be greater than or equal to the current value. If a downgrade assignment request occurs, it is ignored directly, thereby avoiding task duplication or timing disorder caused by milestone rollback.
[0052] like Figure 5 As shown, after completing the milestone update, the system triggers the first scheduling path, corresponding to the synchronous scheduling function `schedule`. During this process, the system first sets the mutex flag `isActionArray` to `YES` to indicate that it is currently in the batch task execution phase, thereby blocking the entry of the second scheduling path based on the RunLoop idle frame during scheduling, ensuring the continuity and atomicity of the scheduling process.
[0053] The system uses an ordered waiting queue, sorted in ascending order by deadline milestones. Starting from the head of the queue, it iterates through the task nodes sequentially, reading the deadline milestone for each node. Since the queue is already ordered during task registration, the traversal can be terminated immediately if a task node's deadline exceeds the current milestone `_event`, without needing to scan subsequent nodes. This avoids a full traversal of the entire queue, making the scheduling time complexity dependent on the actual number of tasks to be executed.
[0054] For each task node that meets the condition `deadline <= _event`, the system removes it from the ordered waiting queue and synchronously executes its corresponding `actionBlock` on the main thread, thus ensuring that the task is completed before its latest execution time. This execution process proceeds sequentially according to the queue until all tasks that meet the condition have been processed.
[0055] Once all eligible task nodes in this scheduling process have completed their execution, the system will restore the mutex flag isActionArray to NO, allowing subsequent scheduling paths based on idle frames to continue operating normally.
[0056] Furthermore, the milestone advancement operations are triggered by key nodes in the application lifecycle. For example, it advances to LaunchBegin when the application:didFinishLaunchingWithOptions: method begins execution, to UIBegin before the loadView method of the homepage ViewController is executed, to LaunchEnd when didFinishLaunchingWithOptions: is about to return, and to UIEnd when the homepage viewDidAppear method completes execution. By binding the task execution timing to the aforementioned milestones with clear business semantics, this embodiment can transform the execution order of startup tasks from traditional code order control to semantic-driven control based on lifecycle nodes.
[0057] Through the aforementioned milestone-driven batch scheduling mechanism, this embodiment achieves centralized execution and timing assurance of critical startup tasks. While ensuring that tasks are completed on time, it significantly reduces scheduling complexity by combining the structural characteristics of ordered queues, and avoids conflicts with idle frame scheduling paths through mutual exclusion control, thereby improving the stability and execution efficiency of the overall scheduling system.
[0058] In one feasible implementation, the above-mentioned triggering of the second scheduling path during the main thread RunLoop idle frame to perform idle scheduling execution on the aforementioned ordered waiting queue includes: Idle scheduling is triggered during the kCFRunLoopBeforeWaiting phase of the main thread's RunLoop. When the above ordered waiting queue includes task nodes, read the task node at the head of the queue; When the deadline of the above task node is less than the preset Future milestone, the above task node is executed in the current idle frame, wherein only one task node is executed in each idle frame.
[0059] Exemplarily, the second scheduling path is not triggered by an explicit call in the business code, but is automatically triggered and implemented relying on the idle frame mechanism of the main thread RunLoop. Specifically, the system pre-registers an observer in the main thread RunLoop to receive callback notifications at the kCFRunLoopBeforeWaiting stage. Since this stage corresponds to the time window before the main thread completes the processing of the current frame and is about to enter the sleep state, it can be regarded as the idle time period between the current frame and the next frame, and this time period is used to perform progressive scheduling processing on the startup tasks in the waiting queue. Path B is triggered by this idle event and runs as the scheduleIdle scheduling entry.
[0060] During the specific execution process, when the main thread enters the kCFRunLoopBeforeWaiting stage, the system first enters the idle scheduling process. At this time, the system first checks the mutex flag isActionArray. If it is detected that the flag is YES, it means that the current first scheduling path is being executed. At this time, the second scheduling path does not participate in task processing, but directly returns and waits to be triggered again by the next idle frame. If the mutex flag allows entry into the scheduling, it further checks whether the ordered waiting queue contains task nodes; when the queue is empty, it means that there are no tasks to be scheduled currently, and the system directly returns, thus ensuring that this scheduling process only incurs a constant-level overhead in the task-free state.
[0061] When it is detected that the ordered waiting queue contains task nodes, the system does not traverse the entire queue, but only reads the task node at the head of the queue and obtains the deadline milestone of this task node. This is because the aforementioned waiting queue has been sorted in ascending order of the deadline milestone during the task registration stage, so the head node naturally corresponds to the task with the highest priority to be processed currently. Further, when it is detected that the deadline milestone of the task node is less than the preset Future milestone, it means that this task is a non-Future task, and its execution does not have to wait until the specific interface completion milestone is reached. In this case, regardless of whether the current milestone status variable _event has reached the deadline milestone corresponding to this task, the system can directly remove the task node from the head of the queue in the current idle frame and execute its corresponding actionBlock, thereby achieving the early consumption of non-critical tasks. In the disclosure, this strategy is clearly stated as: when deadline < DYLaunchEventFuture, immediately remove the task from the head of the queue and execute it to complete some secondary tasks in advance using the inter-frame gap before the home page is rendered.
[0062] Furthermore, to avoid excessive main thread time consumption during a single idle scheduling session, which could affect the subsequent UI refresh rate, this implementation limits the number of tasks executed in each idle frame. Specifically, only one task node is executed in each `kCFRunLoopBeforeWaiting` callback. Once this task is completed, the callback ends immediately and returns to the main thread's `RunLoop`, without processing the next task node. This "single-frame, single-task" scheduling method allows multiple initialization tasks to be evenly distributed across multiple inter-frame gaps for batch execution, thus avoiding main thread blocking caused by concentrated initialization task execution. It also helps to keep the execution time of each session within the frame budget.
[0063] It should be noted that in terms of technology selection, the observer is registered in kCFRunLoopDefaultMode. When the user performs continuous interactive operations such as swiping, the iOS main thread RunLoop automatically switches to UITrackingRunLoopMode. At this time, the observer in the default mode will not be triggered, so the idle scheduling logic will be automatically paused. With the help of this mechanism, the system does not need to add extra interaction state judgments, thus naturally avoiding the interference of initialization tasks on the smoothness of user interactions such as swiping and clicking, thereby further ensuring the responsiveness and user experience of the early interface after startup. Through the above-mentioned second scheduling path based on the RunLoop idle frame, this embodiment achieves low-interference, gradual execution of non-critical startup tasks, making the task scheduling process coordinated with the main thread rendering rhythm, ensuring that system functions are gradually ready while effectively reducing performance jitter during the application cold start phase.
[0064] In one feasible implementation, it further includes: When the deadline milestone of the above task node is equal to the above preset Future milestone, determine whether the current milestone has reached the preset completion milestone on the interface; When the current milestone is greater than or equal to the milestone completed on the above interface, the above task node will be removed from the above ordered waiting queue and the corresponding task will be executed. If the current milestone is less than the milestone completed on the above interface, keep the above task node in the above ordered waiting queue, and repeat the judgment in subsequent idle frames.
[0065] In one feasible implementation, it further includes: During the execution of the first scheduling path and the second scheduling path, a mutual exclusion flag is used to control that the two paths are not executed simultaneously. The execution of the second scheduling path is prohibited when the first scheduling path is executed. If the execution of the first scheduling path is detected while the second scheduling path is being executed, it will return directly. After all startup tasks have completed, keep the idle scheduler returning quickly and remove the RunLoop observer when releasing resources.
[0066] For example, in order to further precisely control the execution timing of different types of startup tasks and ensure the stability and consistency of the dual-path scheduling process, the system introduces a gating judgment mechanism for Future type tasks in the second scheduling path based on the RunLoop idle frame, and combines it with a mutual exclusion flag to achieve coordinated control between the two scheduling paths.
[0067] Specifically, when the system reads a task node from the head of the ordered waiting queue during idle frame scheduling, if it detects that the deadline milestone of that task node is equal to the preset Future milestone, it indicates that the task is a delayed execution type task, and its execution depends on the critical lifecycle node of UI completion. In this case, the system further reads the current milestone state variable and determines whether it has reached the preset UI completion milestone. When it detects that the current milestone is greater than or equal to the UI completion milestone, it indicates that the application's initial screen has been rendered, and the load on the main thread's critical path has been significantly reduced. At this time, the system removes the task node from the ordered waiting queue and executes the corresponding task logic in the current idle frame, thereby achieving delayed triggering of Future type tasks.
[0068] When the current milestone is detected to be less than the interface completion milestone, it indicates that the application is still in the interface building or rendering phase. Executing such a task at this time may put additional pressure on the main thread, thus affecting the smoothness of the interface. Therefore, in this case, the system will not dequeue or execute the task node, but will maintain its original position in the ordered waiting queue and end the current idle frame scheduling. In each subsequent idle frame trigger, the system repeats the above judgment logic until the current milestone meets the execution conditions, thereby achieving delayed scheduling control for Future type tasks.
[0069] Meanwhile, within the overall scheduling system, to avoid concurrent conflicts between the first scheduling path (batch execution based on milestone advancement) and the second scheduling path (gradual execution based on idle frames), a mutex flag is introduced to coordinate and control the two paths. When the first scheduling path is triggered, the system first sets the mutex flag to an active state, prohibiting the second scheduling path from entering the execution flow, thus ensuring the continuity of batch task execution. When the second scheduling path is triggered in an idle frame, the system prioritizes checking the mutex flag. If the first scheduling path is detected to be executing, the system directly terminates the current scheduling and returns to the main thread RunLoop, preventing both paths from simultaneously operating on the ordered waiting queue.
[0070] Once the first scheduling path has completed the execution of all tasks that meet the conditions, the system restores the mutex flag to an inactive state, allowing the second scheduling path to continue executing unfinished tasks in subsequent idle frames. Through this mutex control mechanism, safe scheduling and order guarantees can be achieved in a single-threaded environment without introducing complex thread locks.
[0071] Furthermore, once all startup tasks have completed, the ordered waiting queue will become empty. In this state, the second scheduling path only checks if the queue is empty each time an idle frame is triggered and returns quickly, thus preventing the scheduling system from incurring substantial performance overhead in the later stages of operation. Simultaneously, when scheduling system resources need to be released, such as when the startup scheduler's lifecycle ends or the singleton object is destroyed, the system calls the RunLoop observer removal interface to unregister previously registered observers from the RunLoop and release the corresponding system resources, thereby avoiding invalid callbacks and memory leaks.
[0072] By combining the aforementioned Future task gating mechanism with the dual-path mutual exclusion control strategy, this embodiment not only achieves fine-grained scheduling of tasks with different priorities, but also ensures the stability and high performance of the scheduling process during the critical stages of application startup.
[0073] In summary, this invention introduces a dual-drive scheduling mechanism combining startup milestone gating and RunLoop idle frame awareness. This elevates the execution of SDK initialization tasks from traditional sequential code execution or fixed-time delay execution to an adaptive scheduling method based on business semantics, resulting in significant improvements in startup performance and system maintainability. By distributing non-critical initialization tasks across the main thread's idle time slots for frame-by-frame execution, this invention effectively avoids the concentrated execution of tasks during the startup phase from occupying the first frame's rendering path, thus significantly shortening the time from application startup completion to initial screen display and improving the user-perceived startup speed. By constructing an ordered milestone system and declaring deadline milestones during task registration, the original task execution order, which relied on manual maintenance by developers, is transformed into a structured constraint relationship automatically guaranteed by the scheduling system. This makes task timing dependencies explicit and manageable, reducing the risk of timing errors introduced by version iterations. Furthermore, this invention binds task execution timing to specific business milestones, rather than relying on fixed time delays, enabling scheduling behavior to adapt to different device performance and operating environments, always maintaining consistency with the actual business state and improving system stability and consistency. By employing a "single-frame, single-task" execution strategy during RunLoop idle frames, the execution time of a single task is effectively controlled, ensuring it does not exceed the frame time budget. This guarantees a smooth user experience during interaction, unaffected by background initialization tasks. Finally, this invention utilizes a unified task registration interface and milestone declaration mechanism, allowing new SDKs to integrate into the scheduling system without modifying the core startup code. This achieves a loosely coupled, highly scalable component-based management model, significantly improving system scalability and team collaboration efficiency.
[0074] In one feasible implementation, this method can be invoked in the following manner, with the system exposing two core interfaces to the outside world, and the caller not needing to concern itself with the internal scheduling details:
[0075] The milestone enumeration is defined as follows, and the enumeration values are monotonically increasing:
[0076] Example of usage: Each business module can independently register and launch tasks at any location, without needing to centralize them in AppDelegate:
[0077] In this embodiment, the system predefines a startup event manager, DYLaunchEventManager, which provides a unified task registration interface, act:beforeEvent:, and a milestone advancement interface, setEvent:. The task registration interface receives initialization tasks submitted by various business modules and declares corresponding deadline milestones for these tasks. The milestone advancement interface updates the current milestone status at key nodes in the application lifecycle, thereby triggering milestone-based scheduling execution. Simultaneously, the system predefines a monotonically increasing milestone enumeration, DYLaunchEvent, including DYLaunchEventLaunchBegin, DYLaunchEventUIBegin, DYLaunchEventLaunchEnd, DYLaunchEventUIEnd, and DYLaunchEventFuture. These correspond to the marked stages executed at the start of application startup, the start of homepage interface construction, the end of the startup process, the completion of homepage display, and the completion of homepage display, respectively, thus forming a complete startup lifecycle timing baseline.
[0078] During application startup, business logic actively advances milestones at corresponding lifecycle nodes. For example, `setEvent:DYLaunchEventLaunchBegin` is called when `application:didFinishLaunchingWithOptions:` begins execution; `setEvent:DYLaunchEventUIBegin` is called before `loadView` in the home view controller begins execution; `setEvent:DYLaunchEventLaunchEnd` is called when `application:didFinishLaunchingWithOptions:` is about to return; and `setEvent:DYLaunchEventUIEnd` is called when `viewDidAppear:` completes execution. As these milestones advance, the system schedules tasks in the ordered waiting queue: tasks whose deadlines have been reached are immediately dequeued and executed via the first scheduling path; non-critical tasks can be executed one by one in idle frames via the second scheduling path when the main thread's RunLoop enters the `kCFRunLoopBeforeWaiting` phase; and tasks with a deadline of `DYLaunchEventFuture` are only allowed to execute in idle frames after the current milestone `DYLaunchEventUIEnd` has been reached.
[0079] As can be seen from this embodiment, the present invention distinguishes different types of SDK initialization tasks according to business importance and life cycle constraints, and performs declarative registration through a unified interface. Combined with milestone advancement and RunLoop idle frame scheduling mechanism, it achieves a layered scheduling effect of prioritizing critical tasks, progressively executing secondary tasks, and delaying the processing of Future tasks. This effectively reduces the pressure on the main thread during the startup phase and improves the efficiency of first-screen rendering and the overall user experience.
[0080] Secondly, this invention also proposes an application startup task scheduling system, such as... Figure 6 As shown, the application startup task scheduling method for implementing any one of the first aspects of claim includes: Create unit 21, which is used to create a startup event manager after the application starts, and initialize the current milestone state and the ordered waiting queue; Configuration unit 22 is used to receive the startup tasks registered by each business module and configure a deadline milestone for each startup task. The enumerated time node identifier associated with the startup task is used to characterize the latest execution time boundary of the startup task. The value of the deadline milestone corresponds one-to-one with the system's predefined milestone sequence. Construction unit 23 is used to sort and insert the above-mentioned startup tasks based on the above-mentioned deadline milestones, so as to construct an ordered waiting queue arranged in ascending order of the deadline milestones; The first scheduling unit 24 is used to advance the current milestone during the application lifecycle and trigger the first scheduling path based on the current milestone to execute the startup task that meets the above-mentioned deadline milestone. The second scheduling unit 25 is used to trigger the second scheduling path during the idle frame of the main thread RunLoop to perform idle scheduling execution on the startup tasks in the above-mentioned ordered waiting queue. The execution unit 26 is used to coordinate scheduling through the first scheduling path and the second scheduling path to realize the phased execution of the startup task at key nodes in the life cycle and during idle frames.
[0081] In one feasible implementation, an application-initiated task scheduling system may also perform any step of the method proposed in the first aspect.
[0082] Thirdly, the present invention also proposes an electronic device 300, such as... Figure 7 As shown, it includes a memory 310, a processor 320, and a computer program 311 stored on the memory 310 and executable on the processor. When the processor 320 executes the computer program 311, it implements the steps of the application startup task scheduling method as described in any of the first aspects.
[0083] Fourthly, the present invention also proposes a computer-readable storage medium having a computer program stored thereon, characterized in that, when the computer program is executed by a processor, it implements the steps of the application startup task scheduling method as described in any one of the first aspects.
[0084] It should be noted that the descriptions of each embodiment in the above embodiments have different focuses. For parts that are not described in detail in a certain embodiment, please refer to the relevant descriptions in other embodiments.
[0085] The above embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit them. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of this application.
Claims
1. An application startup task scheduling method, characterized in that, include: After the application starts, a startup event manager is created, and the current milestone state and ordered wait queue are initialized. The system receives startup tasks registered by each business module and configures a deadline milestone for each startup task. The deadline milestone is associated with an enumerated time node identifier of the startup task, which is used to characterize the latest execution time boundary of the startup task. The value of the deadline milestone corresponds one-to-one with the system's predefined milestone sequence. The startup tasks are sorted and inserted based on the cutoff milestones to construct an ordered waiting queue arranged in ascending order of the cutoff milestones; During the application lifecycle, advance the current milestone and trigger the first scheduling path based on the current milestone to execute the startup task that meets the deadline milestone; During the idle frame of the main thread RunLoop, a second scheduling path is triggered to perform idle scheduling execution on the startup tasks in the ordered waiting queue. By coordinating the scheduling of the first scheduling path and the second scheduling path, the startup task can be executed in stages during key lifecycle nodes and idle frames.
2. The application startup task scheduling method according to claim 1, characterized in that, The process of receiving startup tasks registered by each business module and configuring a deadline milestone for each startup task includes: When a task registration request is received, the current milestone status is read; The startup task is executed immediately when the current milestone status is greater than or equal to the deadline milestone; When the current milestone status is less than the deadline milestone, a task node including task execution logic and the deadline milestone is constructed.
3. The application startup task scheduling method according to claim 1, characterized in that, The step of sorting and inserting the startup tasks based on the deadline milestones to construct an ordered waiting queue arranged in ascending order of the deadline milestones includes: Traverse the ordered waiting queue and find the position of the first deadline milestone that is greater than the current task's deadline milestone; Insert the task node into the corresponding position; If no position that meets the conditions is found, the task node is appended to the end of the queue; This ensures that the ordered waiting queue is always kept in ascending order of the deadline milestone.
4. The application startup task scheduling method according to claim 1, characterized in that, The process of advancing the current milestone and triggering the first scheduling path includes: Receive milestone advancement instructions and update the current milestone to a new milestone value, wherein the new milestone value is only allowed to increase monotonically; Traverse the ordered waiting queue and check the deadline milestones of the task nodes one by one, starting from the head of the queue; Dequeue and execute task nodes whose deadline milestones are less than or equal to the current milestone in sequence; The traversal terminates when a task node with a cutoff milestone greater than the current milestone is encountered.
5. The application startup task scheduling method according to claim 1, characterized in that, The step of triggering a second scheduling path during the main thread's RunLoop idle frame to perform idle scheduling execution on the startup tasks in the ordered waiting queue includes: Idle scheduling is triggered during the kCFRunLoopBeforeWaiting phase of the main thread's RunLoop. When the ordered waiting queue includes task nodes, read the task node at the head of the queue; When the deadline of the task node is less than the preset Future milestone, the task node is executed in the current idle frame, wherein only one task node is executed in each idle frame.
6. The application startup task scheduling method according to claim 5, characterized in that, Also includes: When the deadline milestone of the task node is equal to the preset Future milestone, determine whether the current milestone has reached the preset completion milestone. When the current milestone is greater than or equal to the milestone completed on the interface, the task node is removed from the ordered waiting queue and the corresponding task is executed; When the current milestone is less than the milestone completed by the interface, the task node is kept in the ordered waiting queue, and the judgment is repeated in subsequent idle frames.
7. The application startup task scheduling method according to claim 1, characterized in that, Also includes: During the execution of the first scheduling path and the second scheduling path, a mutual exclusion flag is used to control that the two paths are not executed simultaneously; The execution of the second scheduling path is prohibited when the first scheduling path is executed. If the execution of the first scheduling path is detected while the second scheduling path is being executed, it will return directly. After all startup tasks have completed, keep the idle scheduler returning quickly and remove the RunLoop observer when releasing resources.
8. An application startup task scheduling system, used to implement the application startup task scheduling method according to any one of claims 1 to 7, comprising: The creation unit is used to create a startup event manager after the application starts, and to initialize the current milestone state and the ordered wait queue; The configuration unit is used to receive the startup tasks registered by each business module and configure a deadline milestone for each startup task. The deadline milestone is associated with an enumerated time node identifier of the startup task, which is used to characterize the latest execution time boundary of the startup task. The value of the deadline milestone corresponds one-to-one with the system's predefined milestone sequence. A construction unit is used to sort and insert the startup tasks based on the cutoff milestones to construct an ordered waiting queue arranged in ascending order of the cutoff milestones. The first scheduling unit is used to advance the current milestone during the application lifecycle and trigger the first scheduling path based on the current milestone to execute the startup task that meets the deadline milestone. The second scheduling unit is used to trigger the second scheduling path during the idle frame of the main thread RunLoop to perform idle scheduling execution on the startup tasks in the ordered waiting queue. The execution unit is used to coordinate scheduling through the first scheduling path and the second scheduling path to realize the phased execution of the startup task at key nodes in the life cycle and during idle frames.
9. An electronic device, comprising: The memory and processor are characterized in that, when the processor executes a computer program stored in the memory, it implements the steps of the application startup task scheduling method as described in any one of claims 1-7.
10. 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 application startup task scheduling method as described in any one of claims 1-7.