Timed task scheduling method based on dynamic time configuration

The dynamic time-configurable scheduled task method solves the problems of static configuration difficulty in dynamic adjustment and unreasonable resource utilization in existing technologies, and realizes flexible task scheduling without restarting the application, thereby improving the system's adaptability and maintainability.

CN122019100APending Publication Date: 2026-05-12BEIJING HUANENG XINRUI CONTROL TECH +2
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
BEIJING HUANENG XINRUI CONTROL TECH
Filing Date
2026-02-03
Publication Date
2026-05-12

AI Technical Summary

Technical Problem

Existing scheduled task technologies have several drawbacks. Execution intervals must be hard-coded or defined in static configuration files, making dynamic adjustment difficult and impacting system continuity. Fixed intervals are difficult to adapt to fluctuations in workload, leading to inefficient resource utilization. Some solutions rely on complex components or dedicated database tables, increasing system deployment complexity and maintenance costs.

Method used

A time-based scheduled task method based on dynamic time configuration is adopted, which includes steps such as initialization of the single-threaded timed task executor, acquisition and parsing of configuration parameters, updating of task intervals, data cleanup, and release of system shutdown resources during the system startup phase. Dynamic adjustment without restarting the application is achieved through Java standard concurrency utility classes.

Benefits of technology

It significantly improves the flexibility and efficiency of scheduled tasks, enhances the adaptability and maintainability of the system, simplifies the configuration process, reduces human error, optimizes resource utilization, reduces the difficulty of system integration, and improves system performance and stability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122019100A_ABST
    Figure CN122019100A_ABST
Patent Text Reader

Abstract

The invention discloses a timed task scheduling method based on dynamic time configuration, which relates to the technical field of computer software, and comprises the following steps: S1, in a system starting stage, initializing a single-thread timed task actuator, and synchronously triggering a configuration refreshing and task starting process; s2, calling a configuration service to obtain a task execution interval configuration parameter containing a time unit identifier, wherein the configuration service is selected from a database or a configuration center; and S3, analyzing the configuration parameters through a preset time tool class, and converting the configuration parameters into a unified reference time unit. According to the timed task scheduling method based on dynamic time configuration, a dynamic time configuration mechanism is innovatively introduced, so that the flexibility and efficiency of timed task scheduling are remarkably improved, the task execution interval is allowed to be dynamically adjusted according to external configuration during operation, an application does not need to be restarted, and the task execution efficiency is improved. The adaptability and maintainability of the system are greatly enhanced, the configuration process is simplified, and human errors are reduced.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer software technology, specifically to a timed task scheduling method based on dynamic time configuration. Background Technology

[0002] In the field of computer software technology, scheduled task management is one of the key technologies for ensuring stable system operation, and it is widely used in various scenarios such as alarm data processing, cache cleanup, and log archiving. Its core function is to automatically trigger task execution according to preset rules, reducing manual intervention and improving system operation and maintenance efficiency and data processing timeliness. Currently, mainstream scheduled task management implementation methods in the industry include annotation-based fixed-period configuration and professional scheduling framework deployment. These technologies achieve basic automated task management through preset execution intervals, providing important support for the routine operation of various software systems.

[0003] Existing scheduled task technologies have achieved relatively mature implementation models in practical applications, meeting the basic needs of some scenarios. However, some aspects still require optimization. Firstly, the execution interval of most technical solutions needs to be defined through hard-coded code or static configuration files, making dynamic adjustment difficult during operation. If business requirements change and the execution frequency needs to be modified, the application often needs to be restarted, affecting the continuous operation of the system. Secondly, fixed-interval configuration methods are difficult to adapt to dynamic fluctuations in business volume, potentially leading to a mismatch between the execution frequency and actual needs, resulting in inefficient utilization of system resources. Furthermore, some frameworks supporting dynamic scheduling often rely on complex external components or require additional maintenance of dedicated database tables, increasing the deployment complexity and subsequent maintenance costs. To address these issues, we propose a scheduled task method based on dynamic time configuration. Summary of the Invention

[0004] To address the aforementioned technical issues, a method for scheduling scheduled tasks based on dynamic time configuration is provided. This technical solution solves the problems of existing scheduled task scheduling technologies, which often require hard-coding of execution intervals or definition through static configuration files, making dynamic adjustment during operation difficult and requiring application restarts for changes; fixed intervals are difficult to adapt to fluctuations in business volume, easily leading to unreasonable resource utilization; and some frameworks that support dynamic scheduling rely on complex components or maintain dedicated database tables, increasing system deployment complexity and subsequent maintenance costs.

[0005] To achieve the above objectives, the technical solution adopted by the present invention is as follows: A method for scheduling timed tasks based on dynamic time configuration includes the following steps: S1. During the system startup phase, the single-threaded timed task executor is initialized, and the configuration refresh and task startup processes are triggered synchronously. S2. Call the configuration service to obtain the task execution interval configuration parameters containing time unit identifiers. The configuration service is selected from the database or configuration center. S3. Parse the configuration parameters using a preset time utility class and convert them into a unified reference time unit. If the parsed new interval differs from the current execution interval, update the execution interval parameter. S4. Cancel the original scheduled task and reschedule it based on the updated execution interval: first trigger an immediate task execution, and then schedule it periodically according to the interval. S5. During task execution, scan the cache or database for data that meets the preset filtering conditions, filter timed-out data according to the execution interval, and perform cleanup operations. S6. When the system shuts down, the operation of the timed task executor is terminated, and resources are released.

[0006] Preferably, S1 specifically includes: After the system is deployed and started, the scheduled task component is loaded synchronously, and a single-threaded scheduled task executor is initialized based on Java standard concurrency tools. The executor adopts an unbounded task queue design. During executor initialization, the core parameters of the executor and the availability of threads are verified, and the connection status of the configuration service is pre-tested. After the executor is initialized, the configuration refresh process is started through the built-in triggering mechanism, which simultaneously triggers the task start-up preprocessing. In the pre-task startup process, the cache connection establishment and data access layer initialization are completed.

[0007] Preferably, the verification of the executor's core parameters and thread availability specifically involves: The core parameters of the executor are verified, including thread priority, initial capacity of the task queue, and executor startup flag. The Java thread state detection interface is used to determine whether the thread of the single-threaded executor is in a ready state. The scheduling permissions of the executor thread are also checked, including resource access restrictions and thread blocking status. If the core parameters meet the preset threshold and the thread status is normal, the verification is considered successful. If the verification fails, a system alarm will be triggered and a failure log will be recorded, terminating the scheduled task startup process.

[0008] Preferably, S2 specifically includes: The system reads the preset configuration service type identifier in the system configuration file. The identifier is a unique code corresponding to the database or configuration center. If the identifier is a database code, the database connection test interface is called to verify the validity of the JDBC connection parameters. If the identifier is a configuration center code, the service connectivity status is confirmed through the health check API provided by the configuration center. Based on the identifier code and connection verification result, determine the current configuration service type; if no valid identifier is read or the connection verification fails, trigger a configuration service exception alarm and record the reason; Once the determination is complete, the configuration parameter query is executed according to the corresponding service type, including: querying the configuration fields of the preset data table in the database, and calling its configuration query API in the configuration center.

[0009] Preferably, S2 further includes: Extract the corresponding task execution interval configuration parameters using the key-value format of task unique identifier-configuration value; Confirm that the configuration parameters include a time unit identifier, which is a standardized abbreviation of seconds, minutes, hours, and days; Set a timeout threshold for configuration retrieval. If the configuration is not retrieved after exceeding the threshold, a retry mechanism will be triggered. If the number of retries reaches the preset limit and the configuration is still not successfully retrieved, the default configuration parameters will be used, and an exception log will be recorded. After successfully obtaining the configuration parameters, they are transmitted to the parsing process.

[0010] Preferably, S3 specifically includes: Based on the successfully obtained task execution interval configuration parameters, the preset time utility class is called to match the configuration parameter format using regular expressions and verify whether it conforms to the combination rule of numbers + standardized time units. If the format verification fails, the preset default execution interval is used, the format error log is recorded and an alarm is triggered. If the format verification passes, the parameters are parsed according to the preset conversion rules using the time utility class. Extract the currently effective task execution interval parameter and compare it with the parsed new interval parameter. If the new interval is consistent with the current interval value, maintain the current execution interval and terminate this step. If the new interval is inconsistent with the current interval value, update the execution interval parameter to the parsed new interval and record the interval change log.

[0011] Preferably, S4 specifically includes: Check if there is an existing scheduled task and extract its unique identifier; if there is an existing task, call the cancellation interface of the scheduled task executor to terminate the periodic scheduling of the old task. Verify the cancellation status of the old task to confirm that there are no residual execution threads or tasks in the queue to be executed; if the cancellation of the old task fails, trigger a conflict alarm and forcibly terminate the old task process, and record the reason for the failure. Based on the updated execution interval, trigger the immediate execution command for new tasks; Once the immediate task is completed, configure the executor to start a periodic scheduling mechanism at the new interval, bind the new task identifier and execution interval, and store it in the task scheduling registry; Record a task scheduling change log, which includes: old task identifier, new interval value, immediate execution result, and periodic scheduling start time.

[0012] Preferably, S5 specifically includes: Read the system's preset data storage medium type. If it is a cache, establish a cache connection; if it is a database, obtain a connection through the data access layer. Verify the storage medium connection status. If the connection fails, trigger the retry mechanism. If the retry fails to go online, record the exception log and terminate this step. According to the preset business filtering rules, scan the original data in the storage medium that meets the conditions; combine the updated execution interval to calculate the data timeout threshold, that is, the current system time minus the execution interval; filter out the timeout data whose data status meets the preset conditions and whose timestamp is earlier than the timeout threshold, and extract them in batches according to the preset paging parameters; Call the data processing service to perform batch cleanup operations on the timed-out data extracted in batches; Verify the cleanup results and count the number of successfully cleaned and failed cleanup entries. If there is data that failed to be cleaned, record the failure data identifier and reason, and trigger the subsequent retry cleanup mechanism. After the cleanup is complete, close the data storage media connection and release data access resources.

[0013] Preferably, the batch cleanup operation specifically involves: Call the batch cleanup interface of the data processing service, and pass in the unique set of identifiers for the timed-out data in the current batch; The cleanup strategy is adapted according to the storage medium type. The cleanup strategy includes: calling a batch delete command for cache media and executing batch delete SQL for database media. If related data indexes exist, an index cleanup instruction is generated synchronously and executed atomically with the data topic cleanup operation; and the start time, data identifier range, and cleanup strategy type of the current batch cleanup are recorded; Receive the cleanup execution results returned by the data processing service, including the number of success markers, the number of failure markers, and the reason for failure; if the failure rate of a single batch of cleanup exceeds the preset threshold, suspend the cleanup of subsequent batches and trigger an alarm; if the failure rate does not exceed the threshold, continue to execute the batch cleanup operation of the next batch of timed-out data.

[0014] Preferably, S6 specifically includes: The monitoring system shuts down trigger signals, including service shutdown commands, system restart notifications, and active shutdown trigger commands. Detect the current status of the single-threaded timed task executor to determine whether there are tasks currently being executed and tasks in the queue to be executed; if there are unfinished tasks, start the graceful termination mechanism and set the maximum waiting timeout. If there are still unfinished tasks after the timeout, the task process will be forcibly terminated and the task interruption log will be recorded. Call the executor termination interface to shut down the executor core thread and the unbounded task queue; release executor-related resources, including configuration cache data, task scheduling registry information, and memory resources occupied by the executor thread; Verify the executor termination status to confirm that the core thread has been destroyed and that there are no residual resources occupied. If the executor termination fails, trigger a system-level alarm and forcibly release the resource-occupied port. Record the executor termination log, including the reason for shutdown, termination time, resource release list, and details of unfinished tasks.

[0015] Compared with the prior art, the beneficial effects of the present invention are as follows: The time-based task scheduling method proposed in this invention significantly improves the flexibility and efficiency of time-based task scheduling by innovatively introducing a dynamic time configuration mechanism. It allows the task execution interval to be dynamically adjusted according to external configuration at runtime without restarting the application, greatly enhancing the system's adaptability and maintainability. The built-in intelligent time unit parsing function simplifies the configuration process and reduces human error. The ability to automatically identify and process different time formats enhances the system's compatibility and stability. By optimizing the task execution frequency, it effectively avoids resource waste and improves the overall system performance. Its implementation based on standard Java concurrency utility classes eliminates the need for complex frameworks, reduces system integration difficulty, and facilitates expansion to other similar scenarios, demonstrating broad application prospects. Attached Figure Description

[0016] Figure 1 This is a flowchart of the method of the present invention; Figure 2 This is a flowchart for the status detection and execution of scheduled tasks. Detailed Implementation

[0017] The following description is intended to disclose the invention and enable those skilled in the art to implement it. The preferred embodiments described below are merely examples, and other obvious variations will occur to those skilled in the art.

[0018] Reference Figure 1 As shown, a time-based task scheduling method includes the following steps: S1. During the system startup phase, the single-threaded timed task executor is initialized, and the configuration refresh and task startup processes are triggered synchronously. S1 specifically includes: After the system is deployed and started, the scheduled task component is loaded synchronously, and a single-threaded scheduled task executor is initialized based on Java standard concurrency tools. The executor adopts an unbounded task queue design. During executor initialization, the core parameters of the executor and the availability of threads are verified, and the connection status of the configuration service is pre-tested. After the executor is initialized, the configuration refresh process is started through the built-in triggering mechanism, which simultaneously triggers the task start-up preprocessing. In the pre-task startup process, the cache connection establishment and data access layer initialization are completed.

[0019] The specific steps for verifying the core parameters of the executor and the availability of threads are as follows: The core parameters of the executor are verified, including thread priority, initial capacity of the task queue, and executor startup flag. The Java thread state detection interface is used to determine whether the thread of the single-threaded executor is in a ready state. The scheduling permissions of the executor thread are also checked, including resource access restrictions and thread blocking status. If the core parameters meet the preset threshold and the thread status is normal, the verification is considered successful. If the verification fails, a system alarm will be triggered and a failure log will be recorded, terminating the scheduled task startup process.

[0020] When using it, please refer to the above: In the startup phase of traditional scheduled task systems, three core problems often exist: First, the executor initialization lacks parameter and thread availability checks, which can easily lead to abnormal execution of subsequent scheduled tasks due to incorrect thread priority configuration, insufficient task queue capacity, or threads being in a blocked / not ready state, resulting in tasks being lost or thread deadlocks. Second, the executor initialization and configuration refresh, as well as the task startup process, are disconnected, which can easily lead to situations where tasks are triggered before the cache is established or the data access layer is ready, causing data access failures. Third, there is a lack of effective alarms and log records after initialization failures, making it difficult for operations and maintenance personnel to quickly locate the root cause of the problem, such as parameter exceeding limits or insufficient permissions, thus prolonging the troubleshooting time.

[0021] This step utilizes a single-threaded executor with an unbounded queue design to handle sudden task submission demands during startup, preventing task drop due to queue capacity limitations. Through dual verification of core parameters (thread priority, initial queue capacity, etc.) and thread availability (readiness status, scheduling permissions), it mitigates startup risks caused by configuration errors and thread anomalies from the outset, ensuring the executor's basic capabilities are compliant. Synchronous configuration refresh and task startup pre-processing simultaneously initialize cache connections and data access layers, preventing resource dependency loss during task startup. Furthermore, an alarm and logging mechanism for verification failures provides real-time notifications to operations personnel regarding issues such as parameter exceeding limits or threads lacking scheduling permissions, significantly shortening the fault location cycle. Overall, this step, through systematic initialization verification and process synchronization design, addresses the pain points of traditional scheduled task systems, such as poor stability, dependency gaps, and difficult troubleshooting during startup, laying a foundation for reliable execution of subsequent scheduled tasks.

[0022] S2. Call the configuration service to obtain the task execution interval configuration parameters containing time unit identifiers. The configuration service is selected from the database or configuration center. S2 specifically includes: The system reads the preset configuration service type identifier in the system configuration file. The identifier is a unique code corresponding to the database or configuration center. If the identifier is a database code, the database connection test interface is called to verify the validity of the JDBC connection parameters. If the identifier is a configuration center code, the service connectivity status is confirmed through the health check API provided by the configuration center. Based on the identifier code and connection verification result, determine the current configuration service type; if no valid identifier is read or the connection verification fails, trigger a configuration service exception alarm and record the reason; Once the determination is complete, the configuration parameter query is executed according to the corresponding service type, including: querying the configuration fields of the preset data table in the database, and calling its configuration query API in the configuration center.

[0023] S2 further includes: Extract the corresponding task execution interval configuration parameters using the key-value format of task unique identifier-configuration value; Confirm that the configuration parameters include a time unit identifier, which is a standardized abbreviation of seconds, minutes, hours, and days; Set a timeout threshold for configuration retrieval. If the configuration is not retrieved after exceeding the threshold, a retry mechanism will be triggered. If the number of retries reaches the preset limit and the configuration is still not successfully retrieved, the default configuration parameters will be used, and an exception log will be recorded. After successfully obtaining the configuration parameters, they are transmitted to the parsing process.

[0024] When using it, please refer to the above: In existing technologies, the acquisition of task execution interval configuration parameters typically relies on a single, static configuration source, lacking the ability to dynamically identify and adapt to multiple types of configuration services. This results in the system being unable to respond quickly when configuration services switch or become unavailable, leading to configuration acquisition failures or task scheduling interruptions. Traditional methods also lack an active verification mechanism for the connection status of configuration services, often resulting in configuration query timeouts or data inconsistencies due to network jitter, service unavailability, and other issues, affecting system stability. Furthermore, the lack of a unified standard for time unit identifiers in configuration parameters can easily cause parsing errors or deviations in task execution cycles, reducing scheduling accuracy.

[0025] This step achieves dynamic determination and reliable connection of configuration service types through preset configuration service type identifiers and bidirectional connection verification, ensuring the accuracy of configuration queries and service availability. The introduction of timeout thresholds and retry mechanisms, combined with anomaly alarms and default configuration degradation strategies, effectively improves the system's fault tolerance and self-recovery capabilities when configuration services are abnormal. Standardized time unit identifiers ensure the consistency of configuration parameter parsing and the timeliness of task scheduling, providing the system with highly reliable and scalable configuration management support.

[0026] S3. Parse the configuration parameters using a preset time utility class and convert them into a unified reference time unit. If the parsed new interval differs from the current execution interval, update the execution interval parameter. S3 specifically includes: Based on the successfully obtained task execution interval configuration parameters, the preset time utility class is called to match the configuration parameter format using regular expressions and verify whether it conforms to the combination rule of numbers + standardized time units. If the format verification fails, the preset default execution interval is used, the format error log is recorded and an alarm is triggered. If the format verification passes, the parameters are parsed according to the preset conversion rules using the time utility class. Extract the currently effective task execution interval parameter and compare it with the parsed new interval parameter. If the new interval is consistent with the current interval value, maintain the current execution interval and terminate this step. If the new interval is inconsistent with the current interval value, update the execution interval parameter to the parsed new interval and record the interval change log.

[0027] When using it, please refer to the above: In existing technologies, parsing the time unit of configuration parameters often relies on simple string splitting or hard-coded conversion, lacking a unified format specification and robust validation mechanism. This makes parsing prone to failure due to inconsistent configuration formats or incorrect unit identifiers, leading to abnormal task execution cycles. Traditional methods typically lack the ability to compare old and new configuration parameters in real time, triggering a full update process even if the configuration content has not changed substantially, causing unnecessary system overhead. Furthermore, the lack of a fallback mechanism for format errors means that any configuration format error will directly cause task scheduling interruption, affecting system availability. This step uses a preset time utility class combined with regular expressions for strict format validation, ensuring the standardization and parsability of the configuration parameter structure. Real-time comparison of old and new interval parameters enables accurate incremental updates, avoiding invalid operations and improving system efficiency. Introducing a default value fallback strategy and alarm mechanism for format errors effectively enhances the system's fault tolerance and stability, ensuring the continuous and reliable operation of the task scheduling service.

[0028] S4. Cancel the original scheduled task and reschedule it based on the updated execution interval: first trigger an immediate task execution, and then schedule it periodically according to the interval. S4 specifically includes: Check if there is an existing scheduled task and extract its unique identifier; if there is an existing task, call the cancellation interface of the scheduled task executor to terminate the periodic scheduling of the old task. Verify the cancellation status of the old task to confirm that there are no residual execution threads or tasks in the queue to be executed; if the cancellation of the old task fails, trigger a conflict alarm and forcibly terminate the old task process, and record the reason for the failure. Based on the updated execution interval, trigger the immediate execution command for new tasks; Once the immediate task is completed, configure the executor to start a periodic scheduling mechanism at the new interval, bind the new task identifier and execution interval, and store it in the task scheduling registry; Record a task scheduling change log, which includes: old task identifier, new interval value, immediate execution result, and periodic scheduling start time.

[0029] When using it, please refer to the above: In existing technologies, dynamic updates of scheduled tasks typically employ a simple "stop-then-start" approach, lacking precise detection and cleanup mechanisms for old task states. This can easily lead to task thread remnants or duplicate execution, causing data inconsistencies. Traditional solutions often neglect real-time verification when updating execution intervals, directly activating new cycles and failing to quickly respond to the timeliness requirements of configuration changes. Furthermore, the lack of complete task scheduling change traceability creates difficulties for operation and maintenance. This step precisely detects and cancels existing scheduled tasks, combined with a forced termination mechanism to ensure complete cleanup of old tasks, effectively avoiding task conflicts and resource consumption. The "real-time execution + periodic scheduling" update mechanism achieves both immediate verification of configuration changes and ensures the accuracy of subsequent execution cycles. Complete task registry management and change log recording provide the system with traceable scheduling state management capabilities, significantly improving the reliability, real-time performance, and maintainability of dynamic updates of scheduled tasks in a distributed environment.

[0030] S5. During task execution, scan the cache or database for data that meets the preset filtering conditions, filter timed-out data according to the execution interval, and perform cleanup operations. S5 specifically includes: Read the system's preset data storage medium type. If it is a cache, establish a cache connection; if it is a database, obtain a connection through the data access layer. Verify the storage medium connection status. If the connection fails, trigger the retry mechanism. If the retry fails to go online, record the exception log and terminate this step. According to the preset business filtering rules, scan the original data in the storage medium that meets the conditions; combine the updated execution interval to calculate the data timeout threshold, that is, the current system time minus the execution interval; filter out the timeout data whose data status meets the preset conditions and whose timestamp is earlier than the timeout threshold, and extract them in batches according to the preset paging parameters; Call the data processing service to perform batch cleanup operations on the timed-out data extracted in batches; Verify the cleanup results and count the number of successfully cleaned and failed cleanup entries. If there is data that failed to be cleaned, record the failure data identifier and reason, and trigger the subsequent retry cleanup mechanism. After the cleanup is complete, close the data storage media connection and release data access resources.

[0031] The specific steps for performing the batch cleanup operation are as follows: Call the batch cleanup interface of the data processing service, and pass in the unique set of identifiers for the timed-out data in the current batch; The cleanup strategy is adapted according to the storage medium type. The cleanup strategy includes: calling a batch delete command for cache media and executing batch delete SQL for database media. If related data indexes exist, an index cleanup instruction is generated synchronously and executed atomically with the data topic cleanup operation; and the start time, data identifier range, and cleanup strategy type of the current batch cleanup are recorded; Receive the cleanup execution results returned by the data processing service, including the number of success markers, the number of failure markers, and the reason for failure; if the failure rate of a single batch of cleanup exceeds the preset threshold, suspend the cleanup of subsequent batches and trigger an alarm; if the failure rate does not exceed the threshold, continue to execute the batch cleanup operation of the next batch of timed-out data.

[0032] When using it, please refer to the above: In existing technologies, scheduled cleanup tasks often face challenges such as unstable storage media connections, low efficiency in processing large volumes of data, and a lack of atomicity guarantees during the cleanup process. Traditional solutions typically employ full table scans to filter data, which can easily lead to database table locking or cache blocking in high-volume scenarios, impacting normal system operations. Cleanup operations and index updates are often executed in steps, posing a risk of inconsistencies between data and index states. Furthermore, the lack of robust batch processing and retry mechanisms means that a single data cleanup failure can cause the entire batch to roll back or the task to be interrupted.

[0033] This step ensures the reliability of the data access channel by dynamically identifying the storage media type and establishing a robust connection retry mechanism. By dynamically calculating timeout thresholds based on execution intervals, precise data filtering is achieved, preventing the accidental deletion of valid data. The pagination and batch processing strategy effectively controls the memory consumption and performance impact of each operation, ensuring system stability. In particular, the atomic execution of data cleanup and index synchronization operations completely solves the data consistency problem. Furthermore, the intelligent alarm and pause mechanism based on failure rate thresholds provides controllable fault tolerance for batch cleanup tasks, ensuring timely interruption and alarm in case of anomalies, avoiding unnecessary resource consumption. The entire solution significantly improves the execution efficiency, security, and maintainability of data cleanup tasks, providing a solid guarantee for the long-term stable operation of the system.

[0034] S6. When the system shuts down, the operation of the timed task executor is terminated, and resources are released. S6 specifically includes: The monitoring system shuts down trigger signals, including service shutdown commands, system restart notifications, and active shutdown trigger commands. Detect the current status of the single-threaded timed task executor to determine whether there are tasks currently being executed and tasks in the queue to be executed; if there are unfinished tasks, start the graceful termination mechanism and set the maximum waiting timeout. If there are still unfinished tasks after the timeout, the task process will be forcibly terminated and the task interruption log will be recorded. Call the executor termination interface to shut down the executor core thread and the unbounded task queue; release executor-related resources, including configuration cache data, task scheduling registry information, and memory resources occupied by the executor thread; Verify the executor termination status to confirm that the core thread has been destroyed and that there are no residual resources occupied. If the executor termination fails, trigger a system-level alarm and forcibly release the resource-occupied port. Record the executor termination log, including the reason for shutdown, termination time, resource release list, and details of unfinished tasks.

[0035] When using it, please refer to the above: In existing technologies, task termination during system shutdown often employs forced interruption, lacking a graceful exit mechanism. This can easily lead to data loss or inconsistent states of critical tasks currently being executed. Traditional solutions often neglect the cleanup of the pending queue, resulting in task backlog or duplicate execution. Furthermore, incomplete resource release can lead to memory leaks or port occupation, affecting system restarts or causing resource conflicts.

[0036] This step establishes a unified termination entry point by monitoring multiple shutdown signals, ensuring comprehensive coverage of various downtime scenarios. Through graceful task termination and tiered forced termination, it guarantees the completion of critical tasks while preventing the system from failing to shut down due to endless waiting. A robust resource release and status verification mechanism completely eliminates the risk of resource residue, providing a clean environment for rapid system restarts or version updates. Detailed termination logs provide complete traceability for operational analysis, significantly improving system maintainability and reliability. The entire solution achieves a smooth and safe exit of the scheduled task executor at the end of the system's lifecycle, ensuring complete recovery of system resources and ultimate consistency of business data.

[0037] Based on the above steps, the specific implementation method is as follows: Suppose an alarm system needs to periodically clean up "closed but unconfirmed" alarm data, initially configured to clean up every 12 hours. On a certain day, due to increased business pressure, the cleanup frequency needs to be increased to once every 30 minutes. The following is a process simulation of this method in this scenario: 1. After the system starts service deployment, the scheduled task component is automatically initialized, the executor is ready, and the configuration value is retrieved from the database for the first time (assuming it is "12h").

[0038] 2. Configuration and Task Startup: The "12h" value is set to 720 minutes. The system uses this value to start scheduled tasks at intervals: a cleanup is performed immediately, and then every 720 minutes thereafter.

[0039] 3. Dynamically adjust the configuration. Maintenance personnel can change the configuration value to "30m" through the management interface. The scheduled task component will then query the configuration again and obtain the new value "30m".

[0040] 4. The interval update and task restart process interprets "30m" as 30 minutes, which is inconsistent with the current interval (720 minutes). Therefore, the interval is updated and the task is restarted: the original task is canceled, a cleanup is performed immediately, and then every 30 minutes thereafter.

[0041] 5. Task Execution and Data Cleanup: During task execution, scan all "completed but unconfirmed" alarm data from Redis, filter out data entries with an end time earlier than (current time - 30 minutes), and call the service to delete these data and their indexes in batches.

[0042] 6. If the resource management service needs to be restarted or scaled up / down during operation, the executor can be safely shut down via annotations to avoid resource leaks.

[0043] Through the above process, the system can respond to configuration changes without restarting, which not only meets the real-time requirements of business operations, but also improves resource utilization efficiency and system maintainability.

[0044] The foregoing has shown and described the basic principles, main features, and advantages of the present invention. Those skilled in the art should understand that the present invention is not limited to the above embodiments. The embodiments and descriptions in the specification are merely principles of the invention. Various changes and modifications can be made to the invention without departing from its spirit and scope, and all such changes and modifications fall within the scope of the claimed invention. The scope of protection claimed by the appended claims and their equivalents is defined.

Claims

1. A method for scheduling timed tasks based on dynamic time configuration, characterized in that, Includes the following steps: S1. During the system startup phase, the single-threaded timed task executor is initialized, and the configuration refresh and task startup process are triggered synchronously. S2. Call the configuration service to obtain the task execution interval configuration parameters containing time unit identifiers. The configuration service is selected from a database or configuration center. S3. Parse the configuration parameters using a preset time utility class and convert them into a unified reference time unit. If the parsed new interval differs from the current execution interval, update the execution interval parameter. S4. Cancel the original scheduled task and reschedule it based on the updated execution interval: first trigger an immediate task execution, and then schedule it periodically according to the interval. S5. During task execution, scan data that meets preset filtering conditions from the cache or database, filter timed-out data according to the execution interval, and perform cleanup operations. S6. When the system shuts down, the operation of the timed task executor is terminated, and resources are released.

2. The time-based task scheduling method based on dynamic time configuration according to claim 1, characterized in that, S1 specifically includes: After the system is deployed and started, the scheduled task component is loaded synchronously, and a single-threaded scheduled task executor is initialized based on Java standard concurrency tools. The executor adopts an unbounded task queue design. During executor initialization, the core parameters of the executor and the availability of threads are verified, and the connection status of the configuration service is pre-tested. After the executor is initialized, the configuration refresh process is started through the built-in triggering mechanism, which simultaneously triggers the task start-up preprocessing. In the pre-task startup process, the cache connection establishment and data access layer initialization are completed.

3. The method for scheduling timed tasks based on dynamic time configuration according to claim 2, characterized in that, The specific steps for verifying the core parameters of the executor and the availability of threads are as follows: The core parameters of the executor are verified, including thread priority, initial capacity of the task queue, and executor startup flag. The Java thread state detection interface is used to determine whether the thread of the single-threaded executor is in a ready state. The scheduling permissions of the executor thread are also checked, including resource access restrictions and thread blocking status. If the core parameters meet the preset threshold and the thread status is normal, the verification is considered successful. If the verification fails, a system alarm will be triggered and a failure log will be recorded, terminating the scheduled task startup process.

4. The time-based task scheduling method based on dynamic time configuration according to claim 1, characterized in that, S2 specifically includes: The system reads the preset configuration service type identifier in the system configuration file. The identifier is a unique code corresponding to the database or configuration center. If the identifier is a database code, the database connection test interface is called to verify the validity of the JDBC connection parameters. If the identifier is a configuration center code, the service connectivity status is confirmed through the health check API provided by the configuration center. Based on the identifier code and connection verification result, determine the current configuration service type; if no valid identifier is read or the connection verification fails, trigger a configuration service exception alarm and record the reason; Once the determination is complete, the configuration parameter query is executed according to the corresponding service type, including: querying the configuration fields of the preset data table in the database, and calling its configuration query API in the configuration center.

5. The time-based task scheduling method based on dynamic time configuration according to claim 1, characterized in that, S2 further includes: Extract the corresponding task execution interval configuration parameters using the key-value format of task unique identifier-configuration value; Confirm that the configuration parameters include a time unit identifier, which is a standardized abbreviation of seconds, minutes, hours, and days; Set a timeout threshold for configuration retrieval. If the configuration is not retrieved after exceeding the threshold, a retry mechanism will be triggered. If the number of retries reaches the preset limit and the configuration is still not successfully retrieved, the default configuration parameters will be used, and an exception log will be recorded. After successfully obtaining the configuration parameters, they are transmitted to the parsing process.

6. The time-based task scheduling method based on dynamic time configuration according to claim 1, characterized in that, S3 specifically includes: Based on the successfully obtained task execution interval configuration parameters, the preset time utility class is called to match the configuration parameter format using regular expressions and verify whether it conforms to the combination rule of numbers + standardized time units. If the format verification fails, the preset default execution interval is used, the format error log is recorded and an alarm is triggered. If the format verification passes, the parameters are parsed according to the preset conversion rules using the time utility class. Extract the currently effective task execution interval parameter and compare it with the parsed new interval parameter. If the new interval is consistent with the current interval value, maintain the current execution interval and terminate this step. If the new interval is inconsistent with the current interval value, update the execution interval parameter to the parsed new interval and record the interval change log.

7. The time-based task scheduling method according to claim 1, characterized in that, S4 specifically includes: Check if there is an existing scheduled task and extract its unique identifier; if there is an existing task, call the cancellation interface of the scheduled task executor to terminate the periodic scheduling of the old task. Verify the cancellation status of the old task to confirm that there are no residual execution threads or tasks in the queue to be executed; if the cancellation of the old task fails, trigger a conflict alarm and forcibly terminate the old task process, and record the reason for the failure. Based on the updated execution interval, trigger the immediate execution command for new tasks; Once the immediate task is completed, configure the executor to start a periodic scheduling mechanism at the new interval, bind the new task identifier and execution interval, and store it in the task scheduling registry; Record a task scheduling change log, which includes: old task identifier, new interval value, immediate execution result, and periodic scheduling start time.

8. The time-based task scheduling method based on dynamic time configuration according to claim 1, characterized in that, S5 specifically includes: Read the system's preset data storage medium type. If it is a cache, establish a cache connection; if it is a database, obtain a connection through the data access layer. Verify the storage medium connection status. If the connection fails, trigger the retry mechanism. If the retry fails to go online, record the exception log and terminate this step. According to the preset business filtering rules, scan the original data in the storage medium that meets the conditions; combine the updated execution interval to calculate the data timeout threshold, that is, the current system time minus the execution interval; filter out the timeout data whose data status meets the preset conditions and whose timestamp is earlier than the timeout threshold, and extract them in batches according to the preset paging parameters; Call the data processing service to perform batch cleanup operations on the timed-out data extracted in batches; Verify the cleanup results and count the number of successfully cleaned and failed cleanup entries. If there is data that failed to be cleaned, record the failure data identifier and reason, and trigger the subsequent retry cleanup mechanism. After the cleanup is complete, close the data storage media connection and release data access resources.

9. A timed task scheduling method based on dynamic time configuration according to claim 8, characterized in that, The specific steps for performing the batch cleanup operation are as follows: Call the batch cleanup interface of the data processing service, and pass in the unique set of identifiers for the timed-out data in the current batch; The cleanup strategy is adapted according to the storage medium type. The cleanup strategy includes: calling a batch delete command for cache media and executing batch delete SQL for database media. If related data indexes exist, an index cleanup instruction is generated synchronously and executed atomically with the data topic cleanup operation; and the start time, data identifier range, and cleanup strategy type of the current batch cleanup are recorded; Receive the cleanup execution results returned by the data processing service, including the number of success markers, the number of failure markers, and the reason for failure; if the failure rate of a single batch of cleanup exceeds the preset threshold, suspend the cleanup of subsequent batches and trigger an alarm; if the failure rate does not exceed the threshold, continue to execute the batch cleanup operation of the next batch of timed-out data.

10. A timed task scheduling method based on dynamic time configuration according to claim 1, characterized in that, S6 specifically includes: The monitoring system shuts down trigger signals, including service shutdown commands, system restart notifications, and active shutdown trigger commands. Detect the current status of the single-threaded timed task executor to determine whether there are tasks currently being executed and tasks in the queue to be executed; if there are unfinished tasks, start the graceful termination mechanism and set the maximum waiting timeout. If there are still unfinished tasks after the timeout, the task process will be forcibly terminated and the task interruption log will be recorded. Call the executor termination interface to shut down the executor core thread and the unbounded task queue; release executor-related resources, including configuration cache data, task scheduling registry information, and memory resources occupied by the executor thread; Verify the executor termination status to confirm that the core thread has been destroyed and that there are no residual resources occupied. If the executor termination fails, trigger a system-level alarm and forcibly release the resource-occupied port. Record the executor termination log, including the reason for shutdown, termination time, resource release list, and details of unfinished tasks.