Task processing method and device
Through the "single-print, multiple-draw" architecture and multi-threaded parallel rendering processing, the problem of low efficiency in processing high-concurrency printing tasks has been solved, and an efficient, stable and autonomous electronic waybill printing system has been realized, meeting the high-performance printing needs of e-commerce platforms.
Patent Information
- Application Number
- CN202510709178.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-05-29
- Publication Date
- 2025-09-09
AI Technical Summary
In high-concurrency scenarios, existing technologies have low printing task processing efficiency, cannot effectively utilize multi-core CPU resources, and have data security risks and imperfect error handling.
It adopts a "single-print, multiple-draw" architecture, processes multi-threaded parallel rendering and printing tasks, and combines a dynamic thread pool and sliding window mechanism to ensure printing order while improving throughput. It also builds a comprehensive error capture and processing mechanism to achieve an autonomous and controllable electronic waybill ecosystem.
It ensures the sequence and efficiency of printing tasks in high-concurrency scenarios, improves system stability and resource utilization, enhances data security and business autonomy and controllability, and meets the high-performance printing needs of e-commerce platforms.
Smart Images

Figure CN120610672A_ABST
Abstract
Description
Technical Field
[0001] The embodiments of this specification relate to the field of data printing technology, and more particularly to a task processing method. One or more embodiments of this specification also relate to a task processing apparatus, a computing device, a computer-readable storage medium, and a computer program product. Background Art
[0002] With the continuous development of computer technology, computers are able to process various types of tasks to meet the needs of actual application scenarios, for example, performing a printing operation according to a printing task.
[0003] Currently, in the process of executing printing operations according to print tasks, print threads are used to implement file rendering operations and file printing operations; however, when the number of print tasks is large, the processing efficiency of the print tasks is low; therefore, how to improve the processing efficiency of print tasks has become a technical problem that needs to be solved urgently. Summary of the Invention
[0004] In view of this, embodiments of this specification provide a task processing method. One or more embodiments of this specification also relate to a task processing apparatus, a computing device, a computer-readable storage medium, and a computer program product to address technical deficiencies in the prior art.
[0005] According to a first aspect of an embodiment of this specification, a task processing method is provided, including:
[0006] Selecting multiple rendering threads from the rendering thread set, and using the multiple rendering threads to render the to-be-printed information contained in the multiple printing tasks in batches in parallel to generate to-be-printed files corresponding to the multiple printing tasks;
[0007] The printing thread is used to call a printing device to print the files to be printed of the multiple printing tasks.
[0008] According to a second aspect of the embodiments of this specification, there is provided a task processing device, including:
[0009] a rendering module configured to select a plurality of rendering threads from a rendering thread set, and use the plurality of rendering threads to render information to be printed contained in a plurality of printing tasks in batches in parallel to generate files to be printed corresponding to the plurality of printing tasks;
[0010] The printing module is configured to utilize the printing thread to call the printing device to perform printing processing on the to-be-printed files of the multiple printing tasks.
[0011] According to a third aspect of an embodiment of this specification, a computing device is provided, including:
[0012] memory and processor;
[0013] The memory is used to store computer programs / instructions, and the processor is used to execute the computer programs / instructions. When the computer programs / instructions are executed by the processor, the steps of the above-mentioned task processing method are implemented.
[0014] According to a fourth aspect of the embodiments of this specification, a computer-readable storage medium is provided, which stores a computer program / instruction, and when the computer program / instruction is executed by a processor, the steps of the above-mentioned task processing method are implemented.
[0015] According to a fifth aspect of the embodiments of this specification, a computer program product is provided, comprising a computer program / instruction, which implements the steps of the above-mentioned task processing method when executed by a processor.
[0016] One or more embodiments of this specification provide a task processing method that separates file rendering operations from file printing operations. During the printing process, multiple rendering threads can be selected from a rendering thread set and used to render the to-be-printed information contained in multiple print tasks in parallel in batches, generating to-be-printed files corresponding to the multiple print tasks. The printing threads can then be used to call a printing device to print the to-be-printed files for the multiple print tasks. By processing the file rendering and printing operations in parallel through the rendering and printing threads, the efficiency of print task processing is improved, avoiding the problem of low print task processing efficiency when there are a large number of print tasks. BRIEF DESCRIPTION OF THE DRAWINGS
[0017] Figure 1 This is a flowchart of a task processing method provided by one embodiment of this specification;
[0018] Figure 2 It is a timing diagram of sequential printing in a task processing method provided in one embodiment of this specification;
[0019] Figure 3 This is a schematic diagram of a printing task processing system architecture in a task processing method provided in one embodiment of this specification;
[0020] Figure 4 This is a cloud platform architecture diagram of printing software in a task processing method provided in one embodiment of this specification;
[0021] Figure 5 This is a process flow chart of a task processing method provided by one embodiment of this specification;
[0022] Figure 6This is a schematic diagram of the core functions of the Rust system in a task processing method provided in one embodiment of this specification;
[0023] Figure 7 This is a structural diagram of a task processing device provided by one embodiment of this specification;
[0024] Figure 8 This is a structural block diagram of a computing device provided by one embodiment of this specification. DETAILED DESCRIPTION
[0025] The following description sets forth many specific details to facilitate a thorough understanding of this specification. However, this specification can be implemented in many other ways than those described herein, and those skilled in the art can make similar generalizations without violating the scope of this specification. Therefore, this specification is not limited to the specific implementations disclosed below.
[0026] The terms used in one or more embodiments of this specification are for the purpose of describing specific embodiments only and are not intended to limit one or more embodiments of this specification. The singular forms "a," "the," and "the" used in one or more embodiments of this specification and the appended claims are also intended to include plural forms unless the context clearly indicates otherwise. It should also be understood that the term "and / or" used in one or more embodiments of this specification refers to and includes any or all possible combinations of one or more associated listed items.
[0027] It should be understood that although the terms first, second, etc. may be used to describe various information in one or more embodiments of this specification, such information should not be limited to these terms. These terms are only used to distinguish the same type of information from each other. For example, without departing from the scope of one or more embodiments of this specification, the first may also be referred to as the second, and similarly, the second may also be referred to as the first. Depending on the context, the word "if" as used herein may be interpreted as "at the time of" or "when" or "in response to determining".
[0028] In addition, it should be noted that the user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, stored data, displayed data, etc.) involved in one or more embodiments of this specification are all information and data authorized by the user or fully authorized by all parties, and the collection, use and processing of relevant data must comply with the relevant laws, regulations and standards of relevant countries and regions, and provide corresponding operation entrances for users to choose to authorize or refuse.
[0029] In one or more embodiments of this specification, a large model refers to a deep learning model with large-scale model parameters, typically containing hundreds of millions, tens of billions, hundreds of billions, trillions, or even more than ten trillion model parameters. A large model can also be called a cornerstone model / foundation model. It is pre-trained on a large-scale unlabeled corpus to produce a pre-trained model with more than 100 million parameters. This model can adapt to a wide range of downstream tasks and has good generalization capabilities, such as a large language model (LLM) and a multi-modal pre-training model.
[0030] When large models are used in practice, only a small number of samples are needed to fine-tune the pre-trained model and it can be applied to different tasks. Large models can be widely used in natural language processing (NLP), computer vision and other fields. Specifically, they can be applied to computer vision tasks such as visual question answering (VQA), image caption (IC), and image generation, as well as natural language processing tasks such as text-based sentiment classification, text summary generation, and machine translation. The main application scenarios of large models include digital assistants, intelligent robots, search, online education, office software, e-commerce, and intelligent design.
[0031] First, the terms involved in one or more embodiments of this specification are explained.
[0032] Electronic Waybill: A digitally generated logistics waybill containing core data such as shipping and receiving information, logistics codes, and barcodes, replacing traditional paper waybills. The high-concurrency printing system in this method is specifically designed for the generation and output of electronic waybills.
[0033] Single-Print-Multi-Render Architecture: This technology separates printing tasks (single-threaded sequential execution) from rendering tasks (multi-threaded parallel processing), resolving the conflict between high concurrency and guaranteed order. This method implements this architecture in Rust, improving throughput while ensuring printing order.
[0034] Dynamic Thread Pool: A resource management mechanism that dynamically adjusts the number of threads based on system load and the number of printers, assigning each printer its own dedicated thread. This dynamic thread pool avoids the resource waste and contention issues associated with traditional fixed thread pools (e.g., supporting 500 concurrent tasks per printer).
[0035] Sliding Window Mechanism: Through BTreeMap, the task sequence number window is maintained, and only the task with the current expected sequence number is allowed to execute, while the rest of the tasks are temporarily stored and waiting. It can ensure the strict order of non-batch orders (such as using DashMap <String,(u64,BTreeMap<u64,PrintTask> )>Implementation).
[0036] Error Capture Bus: A comprehensive error monitoring system covering both the front-end UI and the Rust backend, including layered processing, two-way feedback, and automatic recovery. This system achieves 99.99% stability and supports real-time location of printer- or order-level anomalies.
[0037] tokio::time::sleep is a function in the Tokio library that implements asynchronous sleep. In Rust's asynchronous programming, tokio::time::sleep is used to pause execution in an asynchronous function for a period of time. It accepts a Duration parameter, which represents the length of the sleep time, and returns a Future that will be automatically resolved after the sleep ends.
[0038] TaskQueue is a distributed task queue service used to execute user tasks in an asynchronous HTTP manner.
[0039] BTreeMap: is an ordered key-value pair collection type, implemented based on the B-tree. It provides an ordered key-value pair storage structure and guarantees the order of the keys.
[0040] With the continuous development of computer technology, computers are able to process various types of tasks to meet the needs of practical application scenarios. For example, executing a print operation based on a print task. Currently, when executing a print operation based on a print task, a print thread is used to perform file rendering and file printing operations. However, when there are a large number of print tasks, the print thread cannot process them, resulting in low print task processing efficiency.
[0041] This method can be applied to the warehousing and logistics scenarios of e-commerce platforms. Specific functions include high-performance electronic waybill generation, intelligent printing scheduling, and multi-device collaborative printing, providing merchants with printing solutions from order fulfillment to logistics distribution.
[0042] This method is part of the "Electronic Waybill Self-Developed Version 2.0 Project"; this project aims to replace Version 1.0 of the electronic waybill system technology based on other institutions, build an independent and controllable electronic waybill ecosystem, enhance data security, and improve logistics and distribution efficiency.
[0043] Since other institutions have started to develop electronic waybill systems, various e-commerce platforms have also followed the trend and actively joined the camp of independently developing electronic waybill systems.
[0044] The core driving force behind the unanimous decision by major e-commerce platforms to build their own electronic waybill systems lies in their shared recognition of the crucial importance of mastering key data (business flows, consumers, and merchants) for e-commerce orders on their platforms. Furthermore, electronic waybills have long been the foundation for collaboration between platforms and external service providers. Based on this, the company launched version 1.0 of the electronic waybill, built on the underlying technology of other institutions. However, with the rapid growth of e-commerce business volume, the risk of exposing millions of daily transaction data flows has increased, further necessitating stricter protection of core business data. Furthermore, in actual implementation, version 1.0 of the electronic waybill faced challenges in quickly and effectively integrating with the customized needs of express delivery service providers. Consequently, and in response to the increasingly prominent demands for data security and personalized services, the development and upgrade of version 2.0 of the self-developed electronic waybill became imperative.
[0045] The rapid growth of e-commerce business has given rise to new demands for electronic waybill systems. Based on this, designing and implementing a high-performance, self-controllable electronic waybill printing system to replace the system built based on the technology of other institutions has become a problem that needs to be solved. In addition, this demand stems from the growing business volume (daily order volume exceeds one million) and the improvement of data security requirements.
[0046] In response to the above problems, the core technical requirements include: High concurrent printing capability: support a computer with ordinary configuration in the warehouse to connect to multiple printers (typical scenarios are 3-10) for concurrent printing. Each printer needs to process 500 waybills concurrently, and the total concurrent capacity of a single machine is up to 2,000 waybills issued at the same time. Printing sequence guarantee: while processing high concurrency, the accurate order of waybill printing must be ensured to avoid logistics chaos caused by disordered printing order. Extreme printing response: The system must achieve ultra-low latency printing response, and the target cold start printing speed must be better than the mainstream platform in the industry. Heterogeneous environment compatibility: support mixed use scenarios of various brands and models of printers in the warehouse to maximize the utilization of equipment resources. Stability requirements: under peak load (such as during promotion period), the system stability must be maintained above 99.99%, and warehouse delivery delays due to system failures are not allowed.
[0047] Before designing this invention, a comprehensive analysis of existing electronic waybill printing solutions and the original 1.0 system on the market revealed the following prominent problems:
[0048] 1. Data security risks.
[0049] The 1.0 version of the electronic waybill, which is based on technology from other institutions, has serious data security risks:
[0050] Other institutions can obtain the platform's performance status, including merchants' shipments and logistics performance.
[0051] Other institutions may obtain the operating conditions of the platform's core merchants through waybill information, including the merchant's transaction volume, contact information, supply chain information, etc.
[0052] Other institutions may obtain user purchasing information on the platform, including category preferences, purchasing power, purchase frequency, etc.
[0053] Based on this, the leakage of these data poses a major risk to the e-commerce ecosystem.
[0054] 2. Technical limitations of existing printing architecture.
[0055] The existing electronic waybill printing system has the following technical bottlenecks in high-concurrency scenarios:
[0056] The conflict between guaranteed order and high concurrency: Traditional printing systems often struggle to guarantee print order when pursuing high concurrency, while emphasizing guaranteed order significantly reduces system throughput. The industry's commonly used "single-threaded sequential processing" or "print lock" solutions exhibit extremely poor performance in high-concurrency scenarios.
[0057] Inefficient resource utilization: Traditional solutions mostly create a separate thread for each print task, resulting in high system resource consumption, a surge in the number of threads, and the inability to dynamically adjust according to system load.
[0058] Coupling rendering and printing: Most systems couple form rendering and printing operations together, making it impossible to utilize multi-core CPUs for parallel rendering, resulting in a waste of CPU resources.
[0059] Simple error handling mechanism: Existing systems generally lack a complete error handling and retry mechanism. Once a printer failure or network anomaly occurs, the entire print queue may be blocked.
[0060] Improper memory management: Electronic waybills contain a large number of resources such as images and barcodes. Existing systems often have problems with memory leaks and untimely resource release, resulting in degraded system performance after long-term operation.
[0061] 3. Business customization needs are difficult to meet.
[0062] Slow response to customized needs: Systems based on the technology of other institutions need to be modified by other institutions when connecting to the customized needs of specific logistics service providers, and the response cycle is long.
[0063] Unable to directly connect to the courier company system: Reliance on a third-party intermediary platform increases system complexity and failure points.
[0064] Limited brand transparency: Electronic waybills are displayed as those from other institutions in the logistics service provider’s backend system, making it impossible to establish brand awareness of the electronic waybills.
[0065] The purpose of this invention is to design a new electronic waybill printing system based on the above business needs and technical challenges. The specific objectives include:
[0066] Achieve a "single print, multiple renders" architecture: Break through the technical architecture limitations of traditional electronic waybill printing and maximize parallel rendering capabilities while ensuring the accuracy of the printing order.
[0067] Break through the contradiction between high concurrency and order guarantee: Design a technical solution that can still guarantee printing order in high concurrency scenarios.
[0068] Maximize system resource utilization: Through advanced thread pool management and task scheduling strategies, fully utilize multi-core CPU resources for parallel processing.
[0069] Build a complete exception handling system: Design a comprehensive error capture and handling mechanism to ensure that the system can maintain stable operation in the face of various abnormal situations.
[0070] Establish an independent and controllable electronic waybill ecosystem: get rid of dependence on third-party technology platforms and achieve data security and business autonomy and control.
[0071] Based on this, a task processing method is provided in this specification. One or more embodiments of this specification also involve a task processing device, a computing device, a computer-readable storage medium and a computer program product, which are described in detail one by one in the following embodiments.
[0072] See also Figure 1 , Figure 1 A flowchart of a task processing method provided according to an embodiment of this specification is shown, which specifically includes the following steps.
[0073] Step 102: Select multiple rendering threads from the rendering thread set, and use the multiple rendering threads to render the to-be-printed information contained in multiple printing tasks in batches in parallel to generate to-be-printed files corresponding to the multiple printing tasks.
[0074] The information to be printed can be understood as information that needs to be printed. The information to be printed can be multimodal data, such as text, images, or templates. For example, the data to be printed can be an image on an electronic waybill (such as a barcode or QR code); or text information on an electronic waybill (such as shipping and receiving information, user information, etc.); or a template that describes the embedding location of images and text.
[0075] The file to be printed can be understood as a file that can be printed. For example, the file to be printed can be an image, a document (such as a PDF document), etc.
[0076] In one or more embodiments provided in this specification, the implementation of parallel rendering using multiple rendering threads includes three aspects: channel design and task scheduling, progressive electronic waybill printpdf component rendering, and resource preloading and caching.
[0077] This article uses user-provided code snippets as an example to provide a detailed explanation, demonstrating channel design and task scheduling, progressive electronic waybill printpdf component rendering, and resource preloading and caching operations.
[0078] Among them, the code for channel design and task scheduling is:
[0079]
[0080]
[0081] The above Rust code involves the use of multithreaded communication mechanisms (channels) and locks, which are used to safely pass tasks (such as drawing tasks, printing tasks, etc.) between multiple components. The first part is to create a channel; use mpsc::channel to create a multiproducer, singleconsumer (multiproducer, singleconsumer) channel; mpsc is a module provided by the Rust standard library, and its full name is "Multiple Producer, Single Consumer"; <drawtask>Indicates that the message type transmitted by the channel is DrawTask (usually some kind of drawing task structure); (1000) indicates that the buffer capacity of the channel is 1000, which means that up to 1000 unconsumed tasks can be cached; draw_tx and draw_rx are the two returned endpoints:
[0082] The second part is to obtain and use the print task sender; PRINT_SENDER is a global variable; it encapsulates a channel sender that can be used to send print tasks; get() is from a container (such as OnceCell, lazy_static, or Mutex <Option<...> >); sender.lock() obtains the mutex lock; guard.send(...) actually sends the print task; specifically, the second part tries to get a sender from the static structure; if it is not set or has been released, the subsequent logic is skipped.
[0083] Among them, the code for rendering the progressive electronic waybill printpdf component is:
[0084]
[0085] This Rust code, written in Rust, is primarily used to iterate over a set of data (such as pages or components) and draw specific components based on their type. The overall structure is a nested loop, designed to handle hierarchical data, such as document rendering and UI component drawing. The code's functionality can be summarized as: iterating over data page by page (or block by block), drawing each component based on its type, with special support for drawing electronic barcodes.
[0086] The specific implementation process is as follows:
[0087] 1. Outer loop: traverse data_list; data_list is a collection (such as Vec <t>), represents a set of data to be processed;
[0088] .iter() means read-only iteration of data_list;
[0089] .enumerate() will get the element's index and reference data at the same time;
[0090] In each loop:
[0091] index: the index of the current item (starting from 0);
[0092] data: a reference to the current item;
[0093] The outer loop is used to process "each page" or "each data block" operations.
[0094] 2. Inner loop: traverse the child components children; children is the set of child elements contained in the current data;
[0095] It is assumed here that each data may contain multiple subcomponents (such as UI elements, drawing objects, etc.);
[0096] In each loop:
[0097] child: current child component object;
[0098] The inner loop is used to process "components in the page", such as text boxes, pictures, barcodes, etc.
[0099] 3. Match the component name and call the drawing function; component_name is a string (or string slice) indicating the type of the current component; use match to determine the component type and call the corresponding drawing logic; if the component type is "OnixBarleyElectronicBarcode", call the draw(...) function under the corresponding module; ... indicates that the parameters required for drawing (which may be context, position, size, etc.) are passed in;
[0100] Among them, the code for resource preloading and caching is:
[0101] if! exists{
[0102] / / If the image does not exist, download and cache it
[0103] download_and_save_image(task_id,url,&img_dir,&file_name).await;
[0104] }
[0105] Image caching to avoid repeated downloads
[0106] Font subset cache to avoid repeated generation
[0107] This Rust code is an asynchronous logic branch judgment statement. Its function is: if a certain image file does not exist (!exists), download it and save it to the specified directory. Among them, exists is a Boolean value (bool), indicating "whether the image already exists"; !exists means "if the image does not exist", execute the following code block; this variable is usually the result of a file system check, such as calling std::fs::metadata() or similar functions to determine whether the file exists. download_and_save_image(...) is an asynchronous function used to download an image from a given URL and save it as a local file; task_id: The ID of the current task, which may be used for logging or tracing; url: The network address of the image; &img_dir: The target directory path for saving the image (String or PathBuf type); &file_name: The file name to be saved; .await: Indicates that this is an asynchronous function called in an asynchronous context and waits for its completion.
[0108] Figure 2 The method is shown to design a sequential printing architecture that supports one computer in the warehouse connected to three to ten printers for concurrent printing (each printer issues 500 labels concurrently, and a total of 2,000 labels are issued simultaneously). It can be divided into the following key modules: Figure 2 The timing diagram in Figure 3 describes the background of this method.
[0109] based on Figure 2 It can be seen that Figure 2 This section describes the multi-threaded concurrent processing flow of the printing system, involving the collaboration of multiple modules. The following is a detailed explanation of the technical content of each part:
[0110] This system is a concurrent printing task processing system that adopts a master-worker structure. The master thread is responsible for initialization, task distribution and coordination, and multiple worker threads execute specific printing tasks in parallel. The key components include:
[0111] 1. A printer pool is used to manage a collection of multiple physical or virtual printer resources. Printer 1 and Printer 2 represent two available printing devices.
[0112] 2. Print queue is one of the core mechanisms of task scheduling. Print task queue 1 and print task queue 2 represent two different task queues.
[0113] 3. The main process / main thread executes by initializing the task queue, creating and preparing multiple print task queues, and waiting for tasks to be queued. It then queues 500 tasks and adds 500 print tasks to the task queue, resulting in a total of 500 tasks in the task queue. These 500 tasks enter the system, awaiting scheduling. It then creates a channel and starts multiple workers: using channels or queues for communication, it passes tasks to multiple worker threads. The workers then return to the loop to receive new tasks. After completing a task, each worker returns to the loop and continues to listen for new tasks.
[0114] 4. Worker execution operations include: receiving tasks, calling functions, and calling predefined functions to handle the tasks, such as parsing data and rendering documents. The start_print_pdf function is the core printing function responsible for starting the PDF file generation and printing process.
[0115] 5. The rendering process and printing process include:
[0116] Clear Font Cache: Clears the font cache used in the previous rendering process to ensure that each rendering is independent and clean.
[0117] Collect text from JSON: parse the JSON data sent by the front end and extract the text information to be printed.
[0118] Execute component main logic: perform layout calculation and drawing logic for each component.
[0119] Process image components: perform special processing on image components, including size adjustment, format conversion, etc.
[0120] Download and save the image: If the image is a remote URL, it needs to be downloaded first and saved locally as a temporary file.
[0121] Build and save PDF: Combine all components into a complete PDF document and save it persistently.
[0122] Print PDF: Call the printer driver interface to send the PDF to the specified printer for output.
[0123] 6. Post-printing processing: After the task is completed, cleanup and notification are required. The specific contents are as follows:
[0124] The task is completed, the result is returned, and the permit is released (Release Permit): If a semaphore is used to control the number of concurrency, a permit should be released at this time, and the "return to worker loop" should be executed again to receive new tasks and wait for the next round of task processing.
[0125] Notify the front-end to display the task completion status and display the print results through the front-end, including success prompts, error messages or download links. The front-end displays the task completion status:
[0126] 7. Semaphore status (Semaphore): Semaphore is an important synchronization mechanism for controlling concurrent access. Here it is used to limit the number of printing tasks running at the same time, including active tasks, waiting tasks, total permissions and other states.
[0127] Figure 3 This is a schematic diagram of the print task processing system architecture, involving the collaboration of multiple technical modules. The following is a detailed explanation of the technical content of each module:
[0128] The drawing task execution module is responsible for rendering the page or document components into printable content (such as PDF pages). The operations performed by the drawing task execution module include: Drawing task start: Indicates that a drawing task is assigned to a thread or Worker to start execution. Execute component drawing: Indicates the drawing operation of each UI component in the page (such as text boxes, tables, images, etc.). Font subsetting: Indicates that the fonts used will be extracted from the complete font library to reduce the size of the PDF file. Component drawing completed: Indicates that all components have been drawn and are ready to proceed to the next step (such as generating a PDF).
[0129] The concurrency control module manages the system's concurrency capabilities, preventing resource exhaustion and improving throughput. The operations performed by the concurrency control module include:
[0130] Semaphore: Controls the number of tasks executed simultaneously to avoid system overload. For example, a maximum of 10 tasks are allowed to be drawn simultaneously. Limit the number of concurrent tasks: Set the maximum number of concurrent tasks to ensure system stability and responsiveness. Concurrent drawing thread pool (3-40 concurrent drawing threads for tasks): Maintains 3 to 40 threads in the thread pool for executing drawing tasks; dynamically adjusting the number of threads can optimize performance based on load conditions. Drawing task processing: Uses threads in the thread pool to handle specific drawing logic. PDF file generation: After all components are drawn, they are combined into a complete PDF document.
[0131] The task monitoring module is used to record and track the lifecycle status of print tasks. This module performs operations such as: print task push logging, which records information such as the time and source of tasks pushed from the frontend or scheduler to the queue; task execution start logging, which marks when a task begins to be processed by a thread or worker; and task sequence number management, which manages task sequence numbers.
[0132] The printer task management module is responsible for interacting with physical printers and managing task execution on printing devices. Operations performed by this module include: adding tasks to the queue. Task queue management implements functions such as priority sorting, timeout retries, and queue cleanup. Updating printer numbers involves selecting the appropriate printer number based on load balancing strategies if multiple printers are available. Submitting tasks to the print thread transfers tasks to the thread responsible for communicating with the printer for final output.
[0133] The task execution log module is used to record key time points and status during task execution. The following operations are performed by the task execution log module: recording the start time, which records the timestamp of the task's start execution; recording the execution time, which records the time spent at each stage of the task's execution; and recording the task completion time, which records the timestamp of the task's complete completion. Log storage refers to the persistent storage of this log information for subsequent analysis, auditing, and troubleshooting.
[0134] The print task scheduling module is the core scheduler of the entire printing system, which determines how tasks are distributed and executed. The functions implemented by this print task scheduling module include: the system supports processing 1 to 500 concurrent tasks. It supports connecting 2 to 5 printers to achieve multi-device printing. Print task scheduling refers to intelligent scheduling based on factors such as printer load, task type, and priority. The task queue is where print tasks to be executed are stored. Pushing a task to the print queue means adding the task to the print queue and waiting for scheduling and execution. Task completion means confirming that the rendering task has been successful. Waiting for printing means that the task is already in the queue waiting to be printed.
[0135] The print task sequential execution module emphasizes serial execution of tasks at the printer level. Even if the system supports concurrent processing, the final output is sequential. The operations performed by this print task sequential execution module include: 1. Printing sequentially with 2-5 print threads in the print queue, which means that 2 to 5 threads are responsible for sending tasks to the printer and executing them sequentially.
[0136] 2. Print task execution means the printer is processing the current task. 3. Print task completion means the print task has been successfully output.
[0137] The logging module, the system's log center, records information about the entire task execution process. Operations performed by the logging module include: Print Task Completion, which marks whether a task has completed successfully. Logging of print task information includes recording task IDs, user information, printer information, execution time, and error messages.
[0138] In one or more embodiments provided in this specification, using the multiple rendering threads to render the to-be-printed information contained in multiple print tasks in batches in parallel to generate the to-be-printed files corresponding to the multiple print tasks includes:
[0139] Selecting a rendering thread queue associated with each print task from the rendering thread queues of the plurality of rendering threads, and storing each print task in the associated rendering thread queue;
[0140] The plurality of rendering threads are used to render the to-be-printed information contained in the printing tasks in the rendering thread queue in batches in parallel to generate to-be-printed files corresponding to the plurality of printing tasks.
[0141] The task processing method provided in this manual is described using its application in the electronic waybill printing scenario as an example. Specifically, when drawing the PDF file corresponding to the electronic waybill, a highly efficient waybill rendering engine is developed using multi-threading technology. This engine parallelizes the waybill template parsing and data rendering processes, fully utilizing modern multi-core CPU resources. The specific implementation method is as follows:
[0142] 1. Obtain a print task from the task queue managed by the intelligent print instruction scheduling system; the task queue is used to store all print tasks, and each print task has been assigned a serial number.
[0143] 2. Send the print task to the rendering task scheduler; the rendering task scheduler obtains a specific number of rendering threads (usually 8-16 num_draw_workers) from the rendering thread resource pool;
[0144] 3. The rendering task scheduler stores the printing tasks in the rendering queues of multiple rendering threads (i.e., rendering thread queues) according to the task priority of the printing tasks. For example, high-priority printing tasks will be stored in the high-priority rendering queue.
[0145] 4. Each rendering thread (num_draw_workers) will obtain the print task from its corresponding rendering thread and extract the data and template (i.e., the information to be printed) corresponding to the print task from the cache.
[0146] 5. Each rendering thread performs rendering processing based on the data and template to obtain the PDF file of the printing task (i.e., the file to be printed).
[0147] Based on the above steps, this method provides the technical content for executing and drawing print tasks. When a print task is executed, the front-end will send the task to the print queue through the start_print_pdf function to draw and generate a PDF. After the PDF is generated, the task is submitted to the printer for printing. The specific function analysis is as follows:
[0148] This detailed explanation uses a user-provided code snippet as an example, demonstrating the execution and rendering of print tasks. This implementation implements a "single print, multiple draw" architecture, fully utilizing multi-core CPUs for parallel rendering while ensuring the correct printing order. The design's robustness is demonstrated by the fact that 2,500 print tasks were processed without any out-of-order processing (a significant improvement over the industry average and leveraging Rust's ownership reclaim capabilities).
[0149]
[0150] The above code explains its functionality: This is an asynchronous function written in Rust that executes a print task. It's used in a multi-threaded, asynchronous print service system, for example, to process print requests in the background, generate a PDF file, and send it to a designated printer. async fn indicates this is an asynchronous function that can execute concurrently within the asynchronous runtime. task:&PrintTask: Passes a reference to a PrintTask, which contains all the information needed for printing. This function explains its functionality: 1. Calls the print function and awaits the result. The above code calls the print_pdf(...) function and uses .await to wait for its completion. print_pdf should be an asynchronous function responsible for sending a PDF file in a specified path to a printer for printing. The following parameters are provided: task.task_id: The print task ID, which identifies this print task. task.printer: The printer name, which specifies the printer to use. task.pdf_path: The PDF file path, which is the path to the file to be printed. task.print_settings: Print settings, including options such as paper size, number of copies, and duplex printing.
[0151] Based on the above examples, the task processing method provided by this method significantly improves the efficiency of PDF file generation in electronic waybill printing scenarios by introducing a multi-threaded parallel rendering mechanism. Specifically, this method decouples the waybill template parsing from the data rendering process and distributes them to multiple rendering threads for parallel execution, fully tapping into and utilizing the computing power of multi-core CPUs, thereby significantly improving the speed of electronic waybill generation and system throughput.
[0152] In addition, the task priority scheduling mechanism enables rapid response and processing of high-priority printing tasks, enhancing the system's task scheduling flexibility and service quality assurance capabilities. Combined with high-speed caching technology, it further reduces I / O latency for template and data loading, improving overall rendering performance. Specifically, the thread priority management function is described as follows:
[0153] A detailed explanation is given using a user-provided code snippet as an example to demonstrate the functionality of thread priority management.
[0154]
[0155] Functional description: The above code is written in Rust and its function is to set the priority of the current thread to the highest (THREAD_PRIORITY_HIGHEST) on Windows systems.
[0156] #[cfg(target_os="windows")] This is a conditional compilation attribute. It indicates that the following function will only be compiled when the target operating system is Windows. pub fn set_thread_priority_max() defines a public function, set_thread_priority_max(); the function's function is to increase the priority of the current thread. const THREAD_PRIORITY_HIGHEST:i32=2; defines a constant representing "highest thread priority"; thread priority values defined in the Windows API are integers, with 2 being the highest level. unsafe blocks are used in ust to perform unsafe operations; let thread_handle:HANDLE=GetCurrentThread(); calls the Windows API function GetCurrentThread() to obtain the handle of the current thread; HANDLE is a type alias for resource handles in Windows. SetThreadPriority(thread_handle,THREAD_PRIORITY_HIGHEST); calls the Windows API function SetThreadPriority() to set the current thread's priority to the highest; this allows the operating system to prioritize scheduling this thread, which is suitable for scenarios requiring high responsiveness or high performance. By increasing the drawing thread priority, ensure that it gets more CPU time.
[0157] In one or more embodiments provided in this specification, before selecting multiple rendering threads from the rendering thread set, the method further includes:
[0158] Determining the number of physical computing units and load status information of the printing device, wherein the physical computing unit is a computing unit that runs a rendering thread;
[0159] Determining an initial number of rendering threads based on the number of units and the load status information, and determining a target number of rendering threads based on a thread number determination rule and the initial number of rendering threads;
[0160] A rendering thread set is created based on the target number of rendering threads, wherein the number of rendering threads included in the rendering thread set is consistent with the target number of rendering threads.
[0161] The physical computing unit may be understood as a unit that can provide computing power for running a rendering thread. For example, the physical computing unit may be a CPU or a GPU.
[0162] The rendering thread set can be understood as a set consisting of multiple rendering threads, and the rendering thread set can be a rendering thread pool.
[0163] The thread number determination rule can be understood as a rule for determining the target number of rendering threads. The thread number determination rule can be multiplying or adding the initial number of rendering threads and a preset parameter.
[0164] Continuing with the above example, the electronic waybill concurrent printing system will dynamically adjust the size and strategy of the rendering thread pool based on the number of connected printers and resource status. The specific implementation is as follows:
[0165] 1. Determine the number of CPU cores available in the current system (i.e., the number of units) and the load status information of the printer (i.e., the load status information).
[0166] 2. Determine the number of rendering threads based on the number of CPU cores and / or load status information.
[0167] For example, the number of CPU cores is used as the number of rendering threads (ie, the initial number of rendering threads), and the number of rendering threads × 2 (ie, the thread number determination rule) is used as the final number of rendering threads (ie, the target number of rendering threads).
[0168] After determining the final number of rendering threads based on the number of CPU cores, the number of currently running rendering threads is determined based on the print load status. When the printer load is high, the number of currently running rendering threads is reduced; when the printer load is low, the number of currently running rendering threads is increased, thereby achieving adaptive load balancing.
[0169] 3. Create multiple rendering threads based on the number of rendering threads, and build a dynamic thread pool (i.e., a rendering thread collection) based on multiple rendering threads.
[0170] Subsequently, based on the number of currently running rendering threads, a corresponding number of rendering threads can be pulled from the dynamic thread pool to execute subsequent rendering tasks.
[0171] Based on the above examples, this method achieves efficient utilization of system resources and intelligent adaptation to the printing load by dynamically adjusting the rendering thread pool. Specifically, when rendering the PDF file corresponding to the electronic shipping form, the system can intelligently determine the target number of rendering threads based on the current number of available CPU cores and the printer's load status, and build a corresponding dynamic thread pool.
[0172] During actual operation, the system dynamically adjusts the number of rendering threads based on the printer's real-time load: reducing the number of threads when the printer load is high to avoid resource contention and printing congestion; increasing the number of threads when the printer load is low to improve overall throughput. This adaptive load balancing mechanism effectively improves system responsiveness and stability while avoiding performance degradation caused by wasted thread resources or excessive competition.
[0173] In one or more embodiments provided in this specification, selecting multiple rendering threads from a rendering thread set, and using the multiple rendering threads to render information to be printed contained in multiple print tasks in batches in parallel to generate files to be printed corresponding to the multiple print tasks, includes:
[0174] receiving the plurality of printing tasks, and assigning a task priority to each of the printing tasks according to task information of each printing task, wherein the task priority is multiple;
[0175] From the rendering thread set, multiple rendering threads associated with the task priority are selected, and the to-be-printed information contained in multiple printing tasks is rendered in batches in parallel using the multiple rendering threads and the task priority to generate to-be-printed files corresponding to the multiple printing tasks.
[0176] The task information may be information describing the printing task, such as the urgency of the order, the destination area, and the like.
[0177] Continuing with the above example, this method can obtain the order urgency and destination area of the electronic waybill, and obtain the print load status of the printer; and determine the corresponding priority (i.e., task priority) for each print task based on the order urgency, destination area, and print load status. Then, the print task is sent to the rendering task scheduler; the rendering task scheduler obtains a specific number of rendering threads from the rendering thread resource pool; and stores the print task in the rendering queue of multiple rendering threads based on the task priority of the print task. Each rendering thread will obtain the print task from its own corresponding rendering thread, and extract the data and template corresponding to the print task from the cache; rendering processing is performed based on the data and template to obtain a PDF file for the print task.
[0178] Based on the above embodiments, it can be seen that this method intelligently assigns corresponding task priorities to each printing task by comprehensively considering the urgency of the order, the destination area information, and the real-time printing load status of the printer. This priority mechanism realizes differentiated scheduling and processing of printing tasks, so that high-priority tasks (such as expedited orders or orders for specific areas) can be rendered and printed first under the premise that system resources permit, thereby effectively improving logistics response efficiency and service quality. In addition, by distributing tasks of different priorities to the queues of corresponding rendering threads, and combining with a multi-threaded parallel rendering architecture, the decoupling and efficient execution of task scheduling and rendering processing are achieved. Each rendering thread independently obtains tasks and performs rendering processing according to its own queue situation, and cooperates with high-speed caching technology to quickly obtain templates and data, which significantly improves the generation efficiency of electronic waybill PDF files and the system throughput.
[0179] Step 104: Using the print thread, call the printing device to print the to-be-printed files of the multiple print tasks.
[0180] Specifically, this method uses task separation and parallel processing to divide the work into two independent phases: "drawing PDF" and "printing PDF." In the drawing phase, multiple threads generate the PDF document in parallel. In the printing phase, a single thread executes the printing tasks sequentially. The specific functions are explained below:
[0181] This section uses a user-provided code snippet as an example to explain in detail the "Draw PDF" and "Print PDF" operations. It should be noted that this method generally uses a num_draw_workers (threads) of 816.
[0182]
[0183] The code above is written in Rust and is used to create a set of asynchronous worker threads to perform certain drawing-related tasks. It utilizes the Tokio asynchronous runtime to process tasks concurrently. The code above does the following:
[0184] Automatically calculates and creates a certain number of asynchronous worker threads based on the number of CPU cores, with each thread responsible for performing "drawing"-related tasks. During this process, a variable needs to be defined: worker_num: represents the "optimal number of worker threads" calculated based on system resources (usually the number of CPU cores). calculate_optimal_workers() is a function not shown in the code and typically returns an integer value, such as the number of logical cores on the CPU. For example, if the CPU has 8 logical cores, then worker_num might be 8. This method multiplies the original optimal number of threads by 2 to determine the final number of worker threads to be created.
[0185] In addition, the above code creates a worker thread; for iin 0..num_draw_workers{...} means that multiple asynchronous tasks are created in a loop. Each loop calls tokio::spawn(...) to create a new asynchronous task. tokio::spawn(...) is an API provided by Tokio, which is used to start an independent task (similar to a thread) in an asynchronous runtime. It schedules the execution of the passed async move{...} block in Tokio's thread pool. async move{...} is an asynchronous closure that can contain asynchronous operations (such as await expressions). Using the move keyword indicates that this closure will capture external variables (i in this example).
[0186] It should be noted that this method also performs task classification and special processing. For drawing tasks (CPU intensive), spawn_blocking is used for processing. For specific processing methods, see the following code:
[0187] let blocking_result=spawn_blocking(move||{
[0188] / / PDF drawing logic (CPU intensive)
[0189] });
[0190] The above code demonstrates how to use the Tokio asynchronous runtime in Rust, allowing for safe execution of blocking or CPU-intensive operations within asynchronous programs. spawn_blocking is a function provided by Tokio, defined in the tokio::task module. move||{...} is a Rust closure, representing an anonymous function. The move keyword indicates that the closure captures ownership of the outer variables. {...} contains the actual PDF drawing logic, which is CPU-intensive. Printing tasks (IO-intensive) are handled using the event loop.
[0191] In the process of concurrent data structure optimization, this method can use DashMap instead of Mutex. <hashmap>, reduce lock contention; and use atomic counters to track task status, as shown in the following code:
[0192] static ref TASK_PUSH_COUNT:AtomicUsize=AtomicUsize::new(0);
[0193] This line of code is the definition of an atomic counter in Rust: This code defines a global static variable called TASK_PUSH_COUNT, which is a thread-safe atomic counter with an initial value of 0. It can be accessed and modified by multiple threads simultaneously without causing data competition problems.
[0194] In one or more embodiments provided in this specification, the step of using a print thread to call a printing device to print the files to be printed of the multiple print tasks includes:
[0195] A print thread is utilized to determine a target print task from the print tasks according to the task identifier of the print task, and a printing device is called to perform print processing on the to-be-printed file of the target print task.
[0196] The task identifier may be understood as information that uniquely identifies a print task, for example, the task identifier may be a serial number, ID, name, etc. The printing device refers to a hardware device used to print files to be printed, for example, a printer.
[0197] Continuing with the above example, the print thread will determine the serial number (i.e., task identifier) of the current print task it receives, determine the print task currently executing the print process (i.e., target print task) from multiple print tasks based on the serial number, and call the printer to print the PDF file of the print task. Specifically, this method provides a solution for task queues and print task allocation, which is implemented as follows: First, a task queue needs to be designed to handle all print tasks. Each task will be queued in order, and secondly, it will be assigned to different printers for processing based on the serial number of the task to ensure that the printing order is not disrupted. The specific function analysis is as follows:
[0198] This user-provided code snippet is used as an example to explain how to assign print tasks to different printers based on their sequence numbers. This code, written in Rust, implements a structure called PrintTaskQueue for managing multiple printer task queues. Its core functionality is to group print tasks by printer and assign an increasing sequence number to each newly added task. The following is a detailed explanation:
[0199]
[0200] Functional description of the above code: The above code executes the data structure definition: PrintTaskQueue; where tasks is a DashMap, which is a thread-safe hash table (similar to HashMap) suitable for concurrent environments. The key (Key) is of type String, representing the name of the printer. The value (Value) is a Vec <initialtask>, which is the task queue of the printer, consists of multiple InitialTasks. add_task is a method of PrintTaskQueue, which is used to add a new task to a printer's task queue. Among them, printer_name:&str: is the name of the printer to be added. task:InitialTask: is the initial task to be added. The specific logic analysis is:
[0201] Step 1: Clone the original task; in order to use the original task and its cloned version in two branches respectively, a clone (task.clone()) is done in advance.
[0202] Step 2: Attempt to retrieve and modify the task queue for the corresponding printer. Here, the DashMap::entry() API is used to check whether the specified key (printer_name) already exists. If so (indicates that a task queue exists for this printer), the .and_modify(...) branch is executed. Modifying the existing queue involves iterating through all tasks in the current queue and finding the largest sequence number. The new task's sequence is set to that maximum value plus one. Other fields are retained from the original task. The new task is then inserted at the end of the task queue.
[0203] Step 3: If the printer does not have a task queue, create a new one. Specifically, if the printer does not have a task queue, create a new task queue (containing only this one task). The sequence number starts at 1. Use the previously cloned task_clone.
[0204] In the above code, we use PrintTaskQueue to maintain the task queue for each printer and design a method to ensure the order of tasks. When a task arrives, it determines whether to print based on the task sequence. If the expected sequence number of the current queue matches the received task, printing is executed; otherwise, the task is placed in the queue and waits.
[0205] Based on the above examples, this method achieves unique identification and orderly scheduling of print tasks by assigning a unique sequence number (i.e., task identifier) to each print task. Based on this sequence number, the print thread can accurately determine the target task to be printed from among multiple pending tasks, thereby ensuring the sequential and controllable nature of the printing process. Furthermore, this mechanism helps avoid issues such as task confusion, duplicate printing, or missed tasks in a multi-threaded environment, thereby improving the stability and reliability of the printing system.
[0206] In one or more embodiments provided in this specification, the task identifier is a task sequence number;
[0207] The utilizing the print thread to determine the target print task from the print tasks according to the task identifier of the print task includes:
[0208] Using the print thread, determining the serial number of the task to be printed, and if the serial number of the task to be printed is consistent with the task serial number of the print task, confirming the print task as the target print task,
[0209] The serial number of the task to be printed is confirmed according to the historical printing tasks of the printing thread in the history of printing processing, and the serial number of the task to be printed is the task serial number corresponding to the printing task that the printing thread currently needs to execute printing processing.
[0210] The serial number of the task to be printed can be understood as the serial number corresponding to the printing task that needs to be printed, for example, the expected serial number.
[0211] Continuing with the above example, during the printing process, the print thread will determine the expected sequence number of the printer and the sequence number of the current print task received. If the two sequence numbers are consistent, the printer will be called to print the current print task, and after completion, the expected sequence number will be increased by 1. The initial expected sequence number is 1.
[0212] Based on the above examples, this method achieves precise synchronization between print tasks and the order in which they are executed by the printer, using the expected sequence number. In a multi-threaded concurrent printing environment, the print thread ensures that tasks are executed in order by comparing the sequence number of the received print task with the expected sequence number of the current printer. This effectively avoids problems such as task confusion, duplicate printing, and out-of-order printing, significantly improving the reliability and stability of the printing process.
[0213] In one or more embodiments provided in this specification, after using the print thread to call the printing device to print the to-be-printed files of the multiple print tasks, the method further includes:
[0214] The print thread is used to update the serial number of the task to be printed based on a preset serial number update rule to obtain an updated serial number of the task to be printed.
[0215] Continuing with the previous example, the printer is called to print the current print job and, upon completion, the expected sequence number is incremented by 1. The initial expected sequence number is 1. This automatically increments the expected sequence number after the current job is printed, forming a continuous and orderly task processing flow. This supports efficient management and precise scheduling of large-scale concurrent print jobs, and is particularly suitable for applications such as electronic shipping orders that require high task order and execution accuracy.
[0216] In one or more embodiments provided in this specification, after determining the serial number of the task to be printed by using the print thread, the method further includes:
[0217] When the task sequence number to be printed is inconsistent with the task sequence number of the printing task, the task sequence number of the candidate printing task stored in the printing thread queue is obtained.
[0218] When the task sequence number of the to-be-printed task is consistent with the task sequence number of the candidate printing task, the candidate printing task is determined as the target printing task, and the printing task is stored as a candidate printing task in the printing thread queue according to the task sequence number.
[0219] The candidate print tasks are sequentially stored in the print thread queue according to the task sequence numbers. The print thread queue can be understood as a queue for storing print tasks, and the print thread queue can be a BTreeMap.
[0220] Continuing with the previous example, the print thread will determine the printer's expected sequence number and the sequence number of the current print job it has received;
[0221] If the two serial numbers are inconsistent, the print task that is arranged in the first position is obtained from the BTreeMap. If the print task is the print task that matches the expected serial number, the printer is called to print the current print task; otherwise, it waits. The BTreeMap uses the serial number as the key to sort the print tasks. Specifically, this method provides a strict sorting system based on the serial number: the function analysis is as follows:
[0222] This section uses a user-provided code snippet as an example to explain in detail how to sort print jobs by sequence number.
[0223]
[0224] The above code is written in Rust and primarily implements a queue system that supports multiple printers and sequential printing tasks. It combines DashMap and BTreeMap to manage the task queues for multiple printers and uses a "sliding window" mechanism to ensure that print tasks are executed in unique, ascending order. Each print task has a unique sequence number; each task is assigned a unique, ascending integer as its sequence number, ensuring controllable task execution order. Furthermore, BTreeMap is used to automatically sort tasks by sequence number. When a task is received, it first checks whether it is the next expected sequence number. If not, it is stored in the BTreeMap and awaits execution. Because the BTreeMap is ordered, tasks can then be retrieved and executed in order. This "sliding window" mechanism is implemented to ensure printing order, a core design principle of the entire logic: a task is only allowed to execute immediately if its sequence number is exactly equal to the current expected sequence number. Otherwise, the task is temporarily cached in the queue until the previous task arrives and updates the expected sequence number. After each task is executed, the expected sequence number is incremented by one, forming a "sliding window" mechanism.
[0225] It should be noted that the above code also defines a global static variable definition: static ref PRINTER_QUEUES:DashMap <String,(u64,BTreeMap<u64,PrintTask> )>=DashMap::new();This is a thread-safe global structure used to store task queue information for each printer: String is the printer name (key); (u64,BTreeMap<u64,PrintTask> ) is a tuple: u64: is the next task sequence number currently expected to be received (that is, the current starting point of the "sliding window"); BTreeMap<u64,PrintTask> : It is a queue of tasks that have been received but not yet processed, sorted by key (serial number); DashMap is a thread-safe hash table suitable for concurrent reading and writing.
[0226] Based on the above embodiments, it can be seen that the present method adopts a task caching and sorting strategy based on the BTreeMap structure, which realizes efficient scheduling and orderly execution of non-continuously arriving printing tasks. When the printing thread detects that the current task sequence number is inconsistent with the printer's expected sequence number, it can automatically find and process the earliest executable matching task from the BTreeMap, thereby avoiding printing stagnation or resource idleness caused by the out-of-order arrival of tasks, and improving the system's fault tolerance and execution efficiency. In addition, BTreeMap automatically sorts printing tasks using the sequence number as the key, so that the system can quickly locate tasks that are consistent with the current expected sequence number in a multi-task concurrent environment, ensuring that the printing process always remains in an orderly state. This mechanism not only improves the utilization rate and task processing throughput of the printing equipment, but also enhances the stability and adaptability of the system in complex network environments or multi-threaded task distribution scenarios.
[0227] In one or more embodiments provided in this specification, before determining the target print task from the print tasks using the print thread according to the task identifier of the print task, the method further includes:
[0228] Receive the plurality of printing tasks, and determine a historical task sequence number corresponding to the printing thread, wherein the historical task sequence number is a task sequence number allocated to the historical printing task;
[0229] Based on the historical task sequence numbers, corresponding task sequence numbers are assigned to the plurality of printing tasks.
[0230] Continuing with the above example, before printing, you need to determine the corresponding serial number for each task, as follows:
[0231] The print command scheduler designs a task queue for each printer to receive all print tasks; and assigns a corresponding sequence number to each print task in the queue.
[0232] First, the print instruction scheduler assigns a sequence number to the current print task according to the historical sequence numbers of different printers (ie, historical task sequence numbers).
[0233] Specifically, get or create a task queue for a given printer through self.tasks.entry(printer_name.to_string()).
[0234] If there is a task queue, the maximum sequence number (max_sequence) in the current queue is calculated, and the sequence number of the print task that currently needs to be stored in the task queue is the maximum sequence number plus one, and it is added to the task queue.
[0235] For example, the maximum serial number corresponding to printer A is 900, so the serial number of the current print task can be 900+1=901.
[0236] Based on the above examples, this method achieves orderly management and precise scheduling of print tasks in a multi-printer environment by maintaining a separate task queue for each printer and assigning incremental unique sequence numbers to new tasks based on the largest existing sequence number in the queue. This mechanism ensures the continuity and uniqueness of task sequence numbers in each printer's corresponding task queue, effectively avoiding issues such as task conflicts, duplicate numbering, and scheduling confusion.
[0237] In one or more embodiments provided in this specification, there are multiple printing devices, and the printing threads correspond one-to-one to the printing devices.
[0238] The method of utilizing the print thread to call a printing device to print the files to be printed of the plurality of print tasks includes:
[0239] The task priorities and the print threads corresponding to the printing devices are used to call the printing devices in batches to print the to-be-printed files of the multiple printing tasks.
[0240] Continuing with the previous example, the intelligent print command scheduling system assigns print tasks to the corresponding print thread based on their sequence number and task priority. This thread then calls the printer to print the print task, thus achieving refined scheduling and orderly execution of print tasks. The system dynamically adjusts the order of task dispatch based on task priority, ensuring that high-priority tasks (such as expedited orders and tasks in key areas) are prioritized by the designated print thread, thereby improving overall print response speed and service quality.
[0241] In one or more embodiments provided in this specification, the step of using a print thread to call a printing device to print the to-be-printed files of the multiple print tasks further includes:
[0242] detecting the printing status information of the printing thread in real time, and terminating the operation of utilizing the printing thread and invoking the printing device to print the files to be printed of the plurality of printing tasks if printing failure is determined based on the printing status information;
[0243] The operation of utilizing the print thread to call a printing device to print the to-be-printed files of the multiple print tasks is re-executed.
[0244] The print status information can be understood as information indicating the print processing status of the print thread. For example, the print status information can be a signal, a fault message, or a
[0245] Continuing with the previous example, this method implements a retry mechanism for task failures. If a task fails due to a printer failure, it can be retried. This prevents all tasks from failing due to a single printer failure. For example, if a task fails due to a printer failure, it can be retried or transferred to another printer for processing.
[0246] One or more embodiments of this specification provide a task processing method that separates file rendering and file printing operations. During the printing process, multiple rendering threads can be selected from a rendering thread set and used to render the to-be-printed information contained in multiple print tasks in parallel, generating to-be-printed files corresponding to the multiple print tasks. The print threads can then be used to call a printing device to print the to-be-printed files for the multiple print tasks. By processing the file rendering and printing operations in parallel through the rendering and printing threads, the efficiency of print task processing is improved, avoiding the problem of low print task processing efficiency when there are a large number of print tasks.
[0247] The following combined Figure 5 , taking the application of the task processing method provided in this specification in the printing of electronic labels as an example, the task processing method is further explained. Figure 5 A flowchart of a task processing method provided by an embodiment of this specification is shown.
[0248] based on Figure 5 As can be seen, for high-concurrency printing scenarios in large-scale e-commerce warehousing and logistics environments, this method takes into account that in high-concurrency printing scenarios, a single workstation in the logistics warehouse needs to be connected to 5-10 printers, and simultaneously handle the concurrent printing demand of tens of thousands of electronic waybills. Therefore, how to achieve high-throughput and low-latency printing operations while ensuring the accuracy of the waybill printing sequence, ensuring that the printing components can output waybills efficiently and stably, and avoiding delays in the logistics and distribution process, has become a technical problem that needs to be solved.
[0249] Based on this, this method designs a high-performance and highly reliable electronic waybill concurrent printing system; taking the electronic waybill printing in the logistics field as an example, Figure 4 The following is a diagram showing the cloud platform architecture of printing software in a task processing method provided in one embodiment of this specification:
[0250] In the printing interface of the Powershell printing software on the cloud platform, a high-concurrency logistics electronic waybill printing operation solution task processing method (i.e., task processing method) that is adapted to multiple operating systems is encapsulated.
[0251] The electronic waybill concurrent printing system consists of the following core technology modules: an intelligent printing instruction scheduling system, a dynamic thread pool management mechanism, an efficient parallel rendering engine, a multi-layer fault tolerance mechanism and status monitoring system, a printing sequence guarantee solution, a heterogeneous environment adaptation framework, and a visual monitoring and management interface.
[0252] 1. Intelligent printing instruction scheduling system: used to build a dedicated scheduler and efficiently obtain printing templates and instructions.
[0253] A dedicated printing instruction scheduler is built into the intelligent printing instruction scheduling system, which adopts a priority queue structure and can perform intelligent scheduling based on the urgency of the order, the destination area and the printer status.
[0254] The system uses an asynchronous pre-fetching mechanism to pre-load the templates and data of subsequent labels while the current label is being printed, effectively reducing the printing interval time.
[0255] The intelligent printing instruction scheduling system implements memory-based high-speed caching, reducing the template acquisition time from an average of 300ms to less than 50ms, significantly improving the system response speed.
[0256] 2. Dynamic thread pool management mechanism: used to dynamically adjust the rendering thread pool according to the number of connected printers, and independently allocate a dedicated printing worker thread for each printer.
[0257] The dynamic thread pool management mechanism in the electronic waybill concurrent printing system implements the following functions:
[0258] Dynamically adjust the size and strategy of the rendering thread pool based on the number of connected printers and CPU resource status. Specifically, the strategy for maximizing CPU resource utilization can be found in the code: let worker_num = calculate_optimal_workers(); / / Dynamically calculated based on the number of CPU cores; This code calculates the "optimal" number of worker threads; The function defined by this code typically determines how many worker threads should be created based on the current system's hardware resources (such as the number of CPU cores and memory); Its return value type is typically an integer value such as usize or u32 / u64. Furthermore, this method implements dynamic thread pool optimization: a worker thread pool model is used instead of creating a new thread for each task; the number of threads is dynamically adjusted based on the number of CPU cores in the system (worker_num * 2).
[0259] Each printer is assigned a dedicated print worker thread, ensuring that print tasks can be processed in parallel without interfering with each other. Furthermore, an adaptive load balancing algorithm is implemented to distribute print tasks based on the processing power and current load of each printer, maximizing overall print throughput.
[0260] 3. Efficient parallel rendering engine: Used to accelerate the rendering process of the face sheet using multi-threading technology and maximize CPU utilization.
[0261] In the concurrent electronic waybill printing system, this method uses multi-threading technology to develop an efficient waybill rendering engine. This engine parallelizes the waybill template parsing and data rendering processes, fully utilizing modern multi-core CPU resources.
[0262] Through fine-grained task decomposition and pipeline processing, the system maximizes CPU utilization during the label generation process. In particular, algorithm optimizations have been made for generating barcodes and QR codes on labels, significantly reducing overall rendering time.
[0263] 4. Multi-layer fault tolerance mechanism and status monitoring system: used to implement a comprehensive error capture bus, covering the front-end UI layer and the Rust back-end processing layer; and designed a two-way error feedback mechanism to ensure that abnormal conditions can be discovered and handled in real time.
[0264] A multi-layer fault-tolerant mechanism and status monitoring system are designed in the electronic waybill concurrent printing system. This monitoring system implements a comprehensive error capture bus, covering the entire link from the front-end UI layer to the Rust back-end processing layer. The monitoring system mechanism includes:
[0265] Layered error handling strategy: Implement different recovery strategies based on the error type.
[0266] Bidirectional error feedback mechanism: ensures that abnormal conditions can be discovered and handled in real time.
[0267] Health self-check mechanism (implemented using the health self-check system): Regularly checks the printer connection status and system resource usage.
[0268] Automatic recovery mechanism: Automatically repair common faults without human intervention.
[0269] Based on the above mechanism, the monitoring system can accurately locate anomalies in specific printers and specific orders, and provide detailed diagnostic information, greatly improving the efficiency of problem troubleshooting.
[0270] 5. Printing sequence guarantee solution: Used to use a linked list structure to ensure the printing order of non-batch orders to avoid business confusion.
[0271] In the concurrent printing system of electronic waybills, a linked list structure and transaction mechanism are used to ensure that the printing order of non-batch orders strictly meets business requirements.
[0272] The system's triple verification mechanism—pre-print verification, in-print monitoring, and post-print confirmation—effectively avoids business disruptions caused by out-of-order orders. Even if some print jobs fail, the system maintains the correct order for the remaining orders and intelligently retries any failed jobs.
[0273] 6. Heterogeneous environment adaptation framework: used to provide compatible solutions, support mixed scenarios of different printing devices, and maximize the utilization of device resources
[0274] The electronic waybill concurrent printing system has developed an adaptation framework that is compatible with multiple printing devices and drivers, supporting mixed usage scenarios of printers of different brands and models.
[0275] Through a unified device abstraction layer and driver adapter, the system can fully utilize the characteristics of various printing devices and maximize the use of device resources. The framework also supports hot plugging, allowing printing devices to be dynamically added or removed without stopping the system.
[0276] 7. Visual monitoring management interface: used to provide real-time printing status, queue monitoring and abnormal alarm functions.
[0277] The electronic waybill concurrent printing system provides an intuitive front-end monitoring interface, including real-time printing status display, print queue monitoring, performance statistics and analysis, and abnormality alerts. This interface allows managers to monitor system operation status in real time, view historical data trends, and perform necessary manual intervention to ensure timely response to issues.
[0278] based on Figure 4 It can be seen that Figure 4 It describes the entire process from the initiation of the print request to task processing, PDF generation and final print output. The following are specific explanations of these contents: The printing system (i.e., the electronic waybill concurrent printing system) includes a monitoring system, which records the system status through system monitoring, including but not limited to the following aspects: Task counter: Counts the number of all tasks in the current system to help understand the system load. Semaphore (record status every 10 seconds): Concurrent access is controlled through the semaphore mechanism, and the system status is recorded regularly (every 10 seconds) to ensure the reasonable allocation and use of system resources. Execution log recording: Records the execution process of each task to facilitate subsequent analysis, debugging or auditing.
[0279] The printing system includes resource management functionality, implemented through a resource manager that manages system resources to ensure efficient use while avoiding resource waste or conflicts. It primarily implements the following functions: Image caching (RAII mode): Caches images used during printing to reduce repeated loading and improve efficiency. Font subset caching (thread-local): Stores only the font subsets actually used in the document, reducing file size and speeding up processing. Temporary file management (automatic cleanup with the Drop feature): Effectively manages various temporary files generated during the printing process to ensure a clean and organized system.
[0280] The execution process of the concurrent electronic form printing system can be as follows: 1. Entry point: A user or front-end application triggers a print operation, entering the system. 2. Front-end print request: The user submits a print request through the front-end interface, specifying the content and parameters to be printed. 3. Add batch print tasks: Based on the user's request, multiple print tasks are added to the system for subsequent processing. 4. Print task storage and sequence number assignment: Each print task is assigned a unique sequence number and stored in the system. 5. Initiate PDF creation tasks: Based on the user-provided data and template, the PDF document generation task is initiated. 6. Rendering phase (multi-threaded parallelism): This phase is the core of PDF generation and utilizes multi-threading to accelerate processing. Specifically, it includes: Rendering task channel (capacity: 1000): Creates a task queue with a capacity of 1000 to ensure sufficient space for pending tasks. Control threads - 1 to - N (N = number of CPU cores * 2): Dynamically creates multiple worker threads based on the number of CPU cores (usually twice the number of CPU cores) to fully utilize hardware resources and improve processing efficiency. Execute PDF generation (blocking computation isolation): execute specific PDF generation logic in each thread, such as font subsetting, component rendering, etc. Generate PDF document (buffwriter zero-copy write): after completing the rendering of all pages, combine them into a complete PDF document. 7. Printing stage (single-threaded sequential execution); this printing system adopts a single-threaded mode in the printing stage and executes printing tasks in sequence, specifically including: Determine the print task channel: select the correct task channel to ensure that the task is correctly scheduled. Determine the printer queue: find the corresponding printer queue, and check the current printer status and task serial number. Determine whether the serial number matches (atomic operation comparison): compare the task serial number with the expected value. If it does not match, the task will be temporarily stored and waited; if it matches, the printing will be executed directly. Process subsequent queue tasks: after completing the current task, continue to process the next task in the queue until all are completed.
[0281] It should be noted that Figure 6 A schematic diagram of the Rust core functions in a task processing method provided by an embodiment of this specification is shown; the Rust core functions include: Concurrency safety primitives: capable of implementing Arc shared reference counting, thread synchronization, and data contention-free guarantees. Lifecycle management: capable of implementing compile-time memory safety checks and resource recycling without GC pauses. Thread local storage: capable of implementing Thread_local encryption and local interleaving of Refcell. Ownership system: capable of achieving zero-copy data transfer and automatic resource release. Asynchronous task system: capable of implementing Tokio asynchronous runtime, Future zero-cost abstraction, and Async / Await syntax. The above core functions can implement specific execution steps or operations in the execution process of the electronic waybill concurrent printing system; the correspondence between the multiple core functions and the execution steps or operations is as follows: Figure 4 Indicated by the dotted arrow.
[0282] Based on the above content, it can be seen that the process of printing electronic waybills using the above-mentioned electronic waybill concurrent printing system specifically includes the following steps.
[0283] Step 1: Utilizing a print order scheduler with a priority queue structure, the system intelligently schedules orders based on order urgency, destination region, and printer status. Furthermore, through an asynchronous prefetch mechanism, templates and data for subsequent orders are preloaded while the current order is being printed, effectively reducing printing intervals.
[0284] Specifically, step 1 is performed by the above-mentioned "intelligent printing instruction scheduling system" and is specifically performed as follows:
[0285] 1. The system receives a print request from the shopping platform and detects whether the hardware configuration of the printer and other hardware is complete based on the print request.
[0286] 2. After confirming that the hardware configuration is complete, send a print request to the shopping platform.
[0287] 3. Receive the electronic waybill sent by the shopping platform based on the print request, where the electronic waybill contains shipping and receiving information, logistics code, barcode and other data.
[0288] 4. Obtain the printing template corresponding to the electronic waybill from the local database. For example, if the electronic waybill is "Zhongtong Express", the printing template corresponding to "Zhongtong Express" will be obtained, and the printing template contains the express logo of "Zhongtong Express".
[0289] 5. Store the printing model and the data contained in the electronic waybill into the cache, and generate a corresponding printing task for the electronic waybill.
[0290] At the same time, through the asynchronous pre-fetching mechanism, the templates and data of subsequent electronic labels are pre-loaded while the current label is being printed, thereby generating corresponding printing tasks for each electronic label.
[0291] 6. Obtain the order urgency and destination area of the electronic waybill, and obtain the printer's print load status;
[0292] 7. Determine a corresponding priority for each print task based on the order urgency, destination area, and print load status. For example, the priority includes: high, medium, and low.
[0293] 8. Determine the corresponding printer for different print tasks based on different priorities. For example, a high-priority print task can be assigned to an idle printer or a printer dedicated to processing high-priority print tasks.
[0294] 9. Print command scheduler: a task queue is designed for each printer to receive all print tasks; and a corresponding sequence number is assigned to each print task in the queue.
[0295] First, the print instruction scheduler assigns a serial number to the current print task based on the historical serial numbers of different printers.
[0296] Specifically, get or create a task queue for a given printer through self.tasks.entry(printer_name.to_string()).
[0297] If there is a task queue, the maximum sequence number (max_sequence) in the current queue is calculated, and the sequence number of the print task that currently needs to be stored in the task queue is the maximum sequence number plus one, and it is added to the task queue.
[0298] For example, the maximum serial number corresponding to printer A is 900, so the serial number of the current print task can be 900+1=901.
[0299] 10. Store the print tasks corresponding to each printer in a task queue and sort the print tasks according to the serial number.
[0300] Specifically, each print task will be queued in the order of the serial number, and can be subsequently assigned to different printers for processing based on the serial number of the print task to ensure that the printing order is not disrupted.
[0301] It should be noted that the corresponding PDF file can be rendered for each print task later, and then, according to the serial number, the print task carrying the PDF file is sent to the printer for printing processing.
[0302] When a print task arrives, the print thread corresponding to the printer will decide whether to execute printing based on the task sequence (serial number);
[0303] If the expected sequence number of the current queue matches the sequence number of the received print job, the printer is called to perform printing;
[0304] Otherwise, the print task is placed in BTreeMap and waits for execution.
[0305] Among them, for the task queue of each printer, this method can use PrintTaskQueue to maintain the task queue of each printer, and at the same time design a method to ensure the sequence of tasks.
[0306] Step 2: The concurrent electronic form printing system dynamically adjusts the size and strategy of the rendering thread pool based on the number of connected printers and resource status. Furthermore, each printer is assigned a dedicated print worker thread, ensuring that print tasks can be processed in parallel without interfering with each other.
[0307] Specifically, step 3 is implemented by the above-mentioned "dynamic thread pool management mechanism", and is specifically executed as follows:
[0308] 1. Determine the number of CPU cores available in the current system and the print load status of the printer.
[0309] 2. Determine the number of rendering threads based on the number of CPU cores or print load status.
[0310] For example, the number of CPU cores is used as the number of rendering threads, and the number of rendering threads multiplied by 2 is used as the final number of rendering threads.
[0311] After determining the final number of rendering threads based on the number of CPU cores, the number of currently running rendering threads is determined based on the print load status. When the printer load is high, the number of currently running rendering threads is reduced; when the printer load is low, the number of currently running rendering threads is increased, thereby achieving adaptive load balancing.
[0312] 3. Create multiple rendering threads based on the number of rendering threads, and build a dynamic thread pool based on multiple rendering threads.
[0313] 4. Based on the number of currently running rendering threads, a corresponding number of rendering threads are pulled up from the dynamic thread pool to execute subsequent rendering tasks.
[0314] 5. Each printer is assigned a dedicated print thread to ensure that print tasks can be processed in parallel without interfering with each other.
[0315] Step 3: When drawing the PDF file corresponding to the electronic waybill, we developed an efficient waybill rendering engine using multi-threading technology. This engine parallelizes the waybill template parsing and data rendering processes, fully utilizing modern multi-core CPU resources.
[0316] Specifically, step 3 is performed by the above-mentioned "efficient parallel rendering engine" and is specifically performed as follows:
[0317] 1. Obtain a print task from the task queue managed by the intelligent print instruction scheduling system; the task queue is used to store all print tasks, and each print task has been assigned a serial number.
[0318] 2. Send the print task to the rendering task scheduler; the rendering task scheduler obtains a specific number of rendering threads (usually 8-16 num_draw_workers) from the rendering thread resource pool;
[0319] 3. The rendering task scheduler stores the printing tasks in the rendering queues of multiple rendering threads according to their task priorities. For example, high-priority printing tasks will be stored in the high-priority rendering queue.
[0320] 4. Each rendering thread (num_draw_workers) will obtain the print task from its corresponding rendering thread and extract the data and template corresponding to the print task from the cache.
[0321] 5. Each rendering thread performs rendering processing based on the data and template to obtain the PDF file of the printing task.
[0322] The specific rendering processing method is:
[0323] First, using font subsetting technology, the required characters (embedded with the necessary font subsets) are analyzed from JSON (text data of the electronic waybill) and converted into text components.
[0324] Secondly, identify the images contained in the electronic waybill, such as barcodes, QR codes, etc.
[0325] Finally, the embedding position of each component in the template is identified, and based on the embedding position, the text component and the image are embedded into the template to obtain the PDF file of the printing task.
[0326] 6. Send the print task containing the PDF file to the intelligent print instruction scheduling system.
[0327] It should be noted that after rendering is completed, the electronic waybill concurrent printing system automatically reclaims cached resources to reduce the risk of memory leaks. Specifically, it provides efficient memory resource management. First, font subsetting technology is used: the required characters are analyzed from JSON and only the necessary font subset is embedded. Second, the Rust ownership feature is used to automatically reclaim resources and reduce the risk of memory leaks. The specific implementation method is shown in the following code:
[0328]
[0329] Functional Description: The above code writes a PDF document (doc) to the memory buffer pdf_bytes, using the buffered writer BufWriter to ensure efficient and secure writing. let mut writer = BufWriter::new(&mut pdf_bytes); creates a BufWriter, a buffered writer. doc.save(&mut writer); calls doc.save(...) to write the document contents to the writer. Here, doc is a structure representing a PDF document (such as PdfDocument). / / The writer is automatically released at this point, indicating the end of its scope. At this point, pdf_bytes contains the entire binary content of the PDF file.
[0330] Step 4: When printing PDF files, a linked list structure is used to ensure the printing order of non-batch orders, avoiding business disruptions. Furthermore, a multi-layered fault-tolerance mechanism and status monitoring system can pinpoint anomalies in specific printers and orders, thus catching any printing errors.
[0331] Specifically, step 4 is implemented by the above-mentioned "printing order guarantee solution", and is specifically implemented as follows:
[0332] 1. Intelligent printing instruction scheduling system sends printing tasks to corresponding printing threads according to the serial number and task priority of printing tasks.
[0333] The scheduling system of this method can send multiple print tasks to the task queues of each printer at once through the batch print task interface. Here, it is necessary to ensure that the printing order of each task and the concurrency capacity of each printer are effectively managed.
[0334] This article uses user-provided code snippets as an example to provide a detailed explanation and demonstrate the operations of batch printing task management.
[0335]
[0336] This Rust code combines the Tauri framework's command macro #[tauri::command] to implement an asynchronous batch printing task adding interface. The code defines the function #[tauri::command]: This is a Tauri command macro, indicating that this function can be called through front-end JavaScript; pub async fn: A public asynchronous function that can be executed in Tauri's asynchronous runtime; tasks: Vec <batchprinttask>: Pass in a task list consisting of multiple BatchPrintTasks; the return value is Result<(),String>: Ok(()) indicates success; Err(String) indicates an error and returns the error message; the function's function is to: take the first task from the task list; if the task list is empty, return the error "Task list is empty"; get the printer name of the task and clone a copy for subsequent use.
[0337] For printing log information, the log system will be used to record current operation information.
[0338] During the execution process, the task list will be traversed and added to the queue one by one (i.e. for task in tasks{}). The specific execution method is: 1. Iterate over each task; 2. Call PRINT_QUEUE.add_task(...) to add the task to the print queue; 3. Construct an InitialTask structure as a parameter; sequence: 0 means that the sequence number is automatically assigned by the queue; return Ok(()) to indicate that the function is executed successfully.
[0339] 2. The print thread determines the expected serial number of the printer and the serial number of the current print job received;
[0340] 3. If the two serial numbers are consistent, the printer is called to print the current print task, and after completion, the expected serial number is increased by 1; wherein, the initial expected serial number is 1.
[0341] 4. If they are not consistent, the first print task in the BTreeMap is retrieved. If the print task matches the expected sequence number, the printer is called to print the current print task; otherwise, the printer waits. The BTreeMap uses the sequence number as a key to sort the print tasks.
[0342] Step 5: During the printing process, the printing status is displayed to the operation and maintenance personnel through the visual monitoring and management interface.
[0343] 1. In the case of printing success or failure, the printing success notification information or printing failure information will be displayed to the operation and maintenance personnel through the visual monitoring management interface.
[0344] 2. This method controls the number of concurrent tasks through semaphores, and detects the status of the print queue in real time based on the semaphore and displays it to the operation and maintenance personnel through a visual monitoring and management interface.
[0345] It should be noted that in order to achieve high-concurrency task processing, this method requires the use of semaphores to control the number of concurrent tasks. The print tasks of each printer are synchronized through semaphores, ensuring that each printer can process a certain number of tasks simultaneously (for example, 500 tasks per printer can be processed concurrently).
[0346] The specific function analysis is as follows:
[0347] This article uses user-provided code snippets as examples to provide detailed explanations and demonstrate how to implement concurrency control and semaphore control.
[0348]
[0349] Functional description of the above code: The above code is written in Rust and is mainly used to implement a semaphore with monitoring function, which is used to limit the number of concurrent tasks in the system. This mode is used to control access to limited resources, such as printers, database connection pools, thread pools, etc. The above code executes the definition of global static variables; PRINT_SEMAPHORE is a global static variable that represents a shared semaphore. The type is Arc <monitoredsemaphore>: Arc represents an atomic reference counting pointer (similar to a smart pointer) used to safely share ownership among multiple threads. MonitoredSemaphore is a custom semaphore structure. When initialized, the maximum number of permits is set to 500, meaning that up to 500 concurrent tasks can execute simultaneously.
[0350] The above code performs a structure definition: The MonitoredSemaphore structure extends the functionality of a regular semaphore, adding monitoring information and the maximum number of concurrent permits (here it is 500). active_tasks: AtomicUsize: is the number of tasks currently running (a thread-safe integer). waiting_tasks: AtomicUsize: is the number of tasks currently waiting to obtain a permit (a thread-safe integer). Through the above fields, developers can monitor the load status of the system, such as how many tasks are queued or running currently.
[0351] Moreover, the above code defines multiple methods: 1. The acquire() method is used to attempt to obtain a semaphore permit. If the current active_tasks < total_permits, the permit is successfully obtained and active_tasks increases. Otherwise, the task must wait until another task calls release() to release the permit. During the waiting period, waiting_tasks increases. The release() method: This method is called when a task is completed to release a permit. active_tasks decreases. If there are waiting tasks, one of them is awakened to continue execution.
[0352] Step 6: Design a retry mechanism when a task fails. If a task cannot be executed due to a printer failure, it can be retried.
[0353] Specifically, this step 6 is a step executed through the above "multi-layer fault tolerance mechanism and status monitoring system", and the specific execution method is as follows:
[0354] Considering that retrying under concurrency requires very careful operations, in order to implement task retry and error handling, this system designs a retry mechanism when a task fails to avoid all tasks failing due to an exception of a certain printer. For example, if a task cannot be executed due to a printer failure, it can be retried or transferred to another printer for processing.
[0355] 1. Task failure retry mechanism.
[0356] Each task may encounter various abnormal situations during execution (such as printer failure, network problems, etc.). This method can design a retry mechanism. This mechanism will try multiple times according to a certain strategy until the task succeeds or the maximum number of retries is reached.
[0357] This method can use tokio::time::sleep to control the retry interval and design a configurable maximum number of retries and the interval between each retry.
[0358] In the retry mechanism, this method sets a maximum number of retries for each task, and the interval between each retry increases incrementally. This design is to prevent the system from being overloaded by excessive retries of faulty tasks during failure recovery.
[0359] 2. Error handling and task rollback
[0360] When a task fails, error handling is required. The reasons for task failure may be printer failure, task parameter errors, etc. To ensure that the print task does not affect subsequent tasks, error handling should include:
[0361] Record error logs.
[0362] Update the task status to Failed and mark it as pending for retry.
[0363] If a task fails after multiple retries, it can be transferred to a backup queue or manual intervention can be performed.
[0364] 3. Log and status updates after task failure
[0365] Whenever a task fails, the reason for the failure needs to be recorded in detail and the task status should be updated. The task status should include:
[0366] web_status: The current status of the task (such as success, failure, pending).
[0367] retry_count: The current number of retries for the task. If the maximum number of retries is exceeded, the task will be automatically marked as failed.
[0368] error_message: Error message, used to help developers diagnose problems.
[0369] 4. Task retry code implementation. The following is the specific implementation plan:
[0370] Processing and retrying after task failure
[0371]
[0372]
[0373] The above Rust code implements a print task failure handling and retry mechanism. It combines asynchronous programming (async fn), logging, task status updates, and task retry functionality, making it suitable for a print service backend or task scheduling system. It defines the main function: handle_task_failure, an asynchronous function that handles print task failures and determines whether to retry. The function's parameters include task: the failed print task object and error: the error message string. The function's execution logic is as follows:
[0374] Set the maximum number of retries. The code is as follows:
[0375] let max_retries = 3; / / maximum number of retries
[0376] let mut retry_count=task.retry_count.unwrap_or(0).
[0377] Function description: Each task can be retried up to 3 times; if the task has not set the number of retries, the default is 0;
[0378] To determine whether a retry is possible, the code is as follows:
[0379] if retry_count <max_retries{
[0380] retry_count += 1;
[0381] log_error(task,error,retry_count); / / Record error log
[0382] Function description: If the maximum number of retries is not reached, increase the retry count by one; call log_error(...) to record the current error message and the number of retries;
[0383] Update the task status to "Retrying", the code is: update_task_status(task,
[0384] "retrying".to_string()).await;
[0385] Function description: Use update_task_status(...) to update the task status to "retrying";
[0386] Wait for an increasing amount of time and try again. The code is as follows:
[0387] let retry_delay = Duration::from_secs(5*retry_count); / / The retry interval will increase
[0388] tokio::time::sleep(retry_delay).await;
[0389] Function description: The retry waiting time increases with the number of times (5 seconds for the first time, 10 seconds for the second time, and 15 seconds for the third time); avoids frequent retries in a short period of time that may lead to resource waste or excessive server pressure;
[0390] Put the task back into the queue. The code is: resend_task_to_queue(task).await;
[0391] Function description: Resend the task to the print queue and wait for the next round of execution;
[0392] Otherwise it is marked as final failure, the code is as follows:
[0393]
[0394] Function description: If the maximum number of retries is exceeded, the task status is set to "failed"; and log_failure(...) is called to output the final failure log;
[0395] The above code defines an auxiliary function, which is described as follows:
[0396] update_task_status: used to update the status of a task; PRINT_QUEUE is a global print task queue manager; the update_task_status(...) method is actually called;
[0397] esend_task_to_queue: used to re-queue the failed task; clone the printer name and task object; and asynchronously call PRINT_QUEUE.add_task(...);
[0398] log_failure: Used to record the final failure log using a logging library (such as log or tracing); contains the task ID, error message, printer name, and number of retries;
[0399] log_error: Used to record the log of each error; including task ID, error message, and current retry count.
[0400] Retry when executing a task
[0401] When the task starts executing, try to print and catch possible errors. If an error is encountered, call handle_task_failure to retry:
[0402]
[0403] This Rust code is an asynchronous print task execution and error handling logic used in a printing system: when a print task starts executing, it attempts to print a PDF file; if printing is successful, the generated file path is returned; if it fails, the handle_task_failure function is called to retry the process.
[0404] execute_print_task_sync, this is an asynchronous function; receives a read-only reference task (type PrintTask); the return value is Result<String,String> :Ok(pdf_path) indicates successful printing and returns the generated PDF path; Err(error_message) indicates printing failure. The execution logic of this function is:
[0405] Execute the print operation, the code is: let print_result = print_pdf(task).await;
[0406] Function description: Call the print_pdf(...) asynchronous function to execute the actual printing logic; .await waits for the result to return;
[0407] Process the print results, the code is:
[0408]
[0409] Function description: If printing is successful (Ok(pdf_path)), the PDF path is returned; if printing fails (Err(error)): call handle_task_failure(task,&error).await to handle the failed task (including retry mechanism); and return an error message string to the upper layer;
[0410] The above code defines a print simulation function: print_pdf, which simulates the printing process. In actual applications, it should be replaced with the logic of actually calling the printer interface. The execution logic of this function is:
[0411]
[0412]
[0413] Function description: Use random numbers to simulate two situations: 50% probability of printing success, returning a hypothetical PDF path; 50% probability of printing failure, returning a "printer failure" error;
[0414] 5. Complete task flow
[0415] Task submission: Each print task will be submitted to the task queue and processed by process_printer_queue_tasks according to the sequence number.
[0416] Task execution: When a task is executed, it will try to call the printing interface. If successful, the task is completed. If it fails, the retry mechanism is triggered.
[0417] Error logging and task status updates: Whenever a task fails, detailed error information is recorded and the task status is updated.
[0418] Task Retry: A task will be retried after a failure until it succeeds or the maximum number of retries is reached.
[0419] 6. Task Status Example
[0420] The status of a task can be divided into the following categories:
[0421] pending: Task waiting to be executed
[0422] retrying: The task is being retried
[0423] completed: The task was successfully executed
[0424] failed: The task finally failed and the maximum number of retries was reached
[0425] 7. Retry times and interval design
[0426] In the retry mechanism, this method sets a maximum number of retries for each task, and the interval between each retry increases incrementally. This design is to prevent the system from being overloaded by excessive retries of faulty tasks during failure recovery. The implementation code is as follows:
[0427] let retry_delay = Duration::from_secs(5*retry_count); / / Incremental retry interval; This code controls the retry interval after a task fails. Based on the current retry count, retry_count, a delay (in seconds) is calculated to wait before retrying after a failure. retry_count is the number of times the task has been retried.
[0428] Step 7: Printing Status Monitoring and Logging
[0429] Throughout the printing process, the electronic delivery system maintains status information for each print job, including success, failure, and in-progress status. This is combined with a log system for real-time monitoring, facilitating problem diagnosis and resolution.
[0430] Based on the above steps, the complete task flow of the electronic waybill concurrent printing system in this method includes: 1. Task submission: Each printing task will be submitted to the task queue and processed by process_printer_queue_tasks according to the sequence number. 2. Task execution: When the task is executed, it will try to call the printing interface. If successful, the task is completed. If it fails, the retry mechanism is triggered. 3. Error log recording and task status update: Whenever a task fails, detailed error information will be recorded and the task status of the task will be updated.
[0431] Based on this, we can see that this system architecture innovation perfectly combines the optimization of printing speed and label clarity, completes the architectural upgrade without interrupting online services, reduces the negative feedback of warehouse operations to zero, and significantly improves user experience and system reliability. Based on the ownership mechanism and type safety characteristics of the Rust language, this solution adopts a self-closed-loop design approach, and cooperates with the microservice decoupling strategy to provide an efficient and reliable architectural paradigm for the order processing system. The solution fully utilizes Rust's concurrency safety and zero-cost abstraction advantages, dares to completely reconstruct the traditional order processing process, and realizes the optimization of the entire process from order receipt, data verification, business processing to bill printing. It provides a high-quality Rust-based model for the electronic label order processing architecture in the e-commerce field.
[0432] The technical effects achieved by the electronic waybill concurrent printing system include:
[0433] Rust-driven printing processing architecture: Shifting from front-end control to Rust for printing sequence management and drawing processing significantly improves system performance and stability. This architecture achieves a 99% overall printing success rate and an average printing speed of 1.83 seconds.
[0434] Drawing thread pool design: Through the design of init drawing thread pool and independent single thread, high concurrent processing capabilities are achieved, effectively meeting the large-scale printing demand of 1.4 million orders per day, bringing the penetration rate of the new architecture to 72%.
[0435] Comprehensive error bus solution: Combining front-end error capture and RUST feedback mechanism with RUST thread error capture itself, a complete error handling system is built, making the printing success rate of each platform reach more than 98% (Win10 99.08%, Win7 99.96%, Mac 98.47%).
[0436] Non-batch single-threaded sequence guarantee solution: uses a linked list structure to ensure the sequential execution of printing tasks, solves the sorting problem in a multi-threaded environment, and improves printing accuracy.
[0437] The online mixed printing mode is compatible with heterogeneous solutions: it supports multiple operating systems (Windows 7 / 10 and Mac) and printing scenarios, achieving high-performance printing in different environments, and excellent printing speed performance on all platforms (Win10 1.54K seconds, Win7 [low-end machine] 2.58K seconds / order [including 400ms number retrieval]).
[0438] In the above business context, the present invention designs a special solution for high-concurrency printing scenarios in large-scale e-commerce warehousing and logistics environments. The specific characteristics of this scenario may be: a single workstation needs to be connected to 5-10 printers, and at the same time handle the concurrent printing needs of tens of thousands of electronic waybills. The key technical challenge is: how to achieve high-throughput, low-latency printing operations while ensuring the accuracy of the waybill printing sequence, ensuring that the printing component can output the waybill efficiently and stably, and avoiding delays in the logistics and distribution links.
[0439] The effects that can be achieved through this method include: directly avoiding the risk of data leakage caused by other institutions. Preventing other institutions from obtaining the performance of the platform, including the merchant's delivery and logistics performance; blocking the possibility of obtaining the operating conditions of the platform's core merchants through waybill information, including the merchant's transaction volume, contact information, supply chain information, etc.; protecting the purchase information of platform users, including category preferences, purchasing power, purchase frequency, etc.; protecting the security of business flow information, blocking the platform merchants from diverting private domains or transferring to other platforms; shortening and simplifying the establishment of customized requirements with logistics service providers; no modification is required, directly connecting to the express company system; expanding other business scenarios: such as interception, package discount anomaly monitoring, etc.; reducing the procurement cost of electronic waybills (the procurement cost is based on 1 million orders per day, and is expected to be 1.5 million per year. The procurement price in 2024 may increase). In addition, high-throughput and low-latency printing operations are achieved to ensure that the printing components can output waybills efficiently and stably, avoiding delays in the logistics and distribution links.
[0440] Furthermore, in practical applications, this method can be used to design a sequential printing architecture that supports concurrent printing from one computer in the warehouse to three to ten printers (each printer can issue 500 labels concurrently, for a total of 2,000 labels). Its implementation effects and business value include:
[0441] This solution has been proven to operate stably across multiple large e-commerce warehouses, achieving significant results. The solution's processing capacity has consistently supported high-load scenarios, with an average daily output of 550,000 electronic waybills and a peak processing capacity of 40,000 orders per hour. It has successfully integrated with 178 ISV partners, covering over 90% of logistics scenarios. Its printing performance has been optimized, achieving an average print speed of 1.6 seconds per order on Windows 10, with a cold start print speed (1.2 seconds) exceeding that of mainstream platforms. System stability has also been improved, achieving 99.99% continuous operational stability, effectively preventing shipment delays due to printing issues.
[0442] Business value: When this system is running, there are no waiting times, order jams, or delayed delivery within the warehouse, significantly improving logistics delivery efficiency. In addition, in addition to the existing electronic waybill printing scenario, this method can also be expanded to the following scenarios:
[0443] Full-link logistics tracking system: Based on the acquired data, a full-link logistics tracking system is built from merchant shipment to user receipt.
[0444] Intelligent warehouse and distribution management system: Integrates printing data with the warehouse management system to provide more intelligent warehousing and distribution decision support.
[0445] Intelligent interception of abnormal orders: Based on the characteristics of the delivery order data, an abnormal order recognition model is built to automatically intercept suspicious orders.
[0446] Multi-format printing solution: Expand the technical framework to other high-concurrency printing scenarios such as invoices and receipts.
[0447] Business data analysis platform: Based on electronic waybill data, establish multi-dimensional analysis models such as logistics efficiency and regional distribution to provide support for business decision-making.
[0448] Corresponding to the above method embodiment, this specification also provides a task processing device embodiment, Figure 7 FIG1 shows a schematic diagram of the structure of a task processing device provided by an embodiment of this specification. Figure 7 As shown, the device includes:
[0449] The rendering module 702 is configured to select multiple rendering threads from the rendering thread set, and use the multiple rendering threads to render the to-be-printed information contained in multiple print tasks in batches in parallel to generate to-be-printed files corresponding to the multiple print tasks;
[0450] The printing module 704 is configured to use the printing thread to call the printing device to print the to-be-printed files of the multiple printing tasks.
[0451] Optionally, the printing module 704 is further configured to:
[0452] A print thread is utilized to determine a target print task from the print tasks according to the task identifier of the print task, and a printing device is called to perform print processing on the to-be-printed file of the target print task.
[0453] Optionally, the task identifier is a task sequence number;
[0454] The printing module 704 is further configured to:
[0455] Using the print thread, determining the serial number of the task to be printed, and if the serial number of the task to be printed is consistent with the task serial number of the print task, confirming the print task as the target print task,
[0456] The serial number of the task to be printed is confirmed according to the historical printing tasks of the printing thread in the history of printing processing, and the serial number of the task to be printed is the task serial number corresponding to the printing task that the printing thread currently needs to execute printing processing.
[0457] Optionally, the printing module 704 is further configured to:
[0458] When the task sequence number to be printed is inconsistent with the task sequence number of the printing task, the task sequence number of the candidate printing task stored in the printing thread queue is obtained.
[0459] When the task sequence number of the to-be-printed task is consistent with the task sequence number of the candidate printing task, the candidate printing task is determined as the target printing task, and the printing task is stored as a candidate printing task in the printing thread queue according to the task sequence number.
[0460] The candidate printing tasks are stored in the printing thread queue in order according to the task sequence numbers.
[0461] Optionally, the task processing device further includes a sequence number allocation module configured to:
[0462] Receive the plurality of printing tasks, and determine a historical task sequence number corresponding to the printing thread, wherein the historical task sequence number is a task sequence number allocated to the historical printing task;
[0463] Based on the historical task sequence numbers, corresponding task sequence numbers are assigned to the plurality of printing tasks.
[0464] Optionally, the rendering module 702 is further configured to:
[0465] Selecting a rendering thread queue associated with each print task from the rendering thread queues of the plurality of rendering threads, and storing each print task in the associated rendering thread queue;
[0466] The plurality of rendering threads are used to render the to-be-printed information contained in the printing tasks in the rendering thread queue in batches in parallel to generate to-be-printed files corresponding to the plurality of printing tasks.
[0467] Optionally, the task processing device further includes a thread set construction module configured to:
[0468] Determining the number of physical computing units and load status information of the printing device, wherein the physical computing unit is a computing unit that runs a rendering thread;
[0469] Determining an initial number of rendering threads based on the number of units and the load status information, and determining a target number of rendering threads based on a thread number determination rule and the initial number of rendering threads;
[0470] A rendering thread set is created based on the target number of rendering threads, wherein the number of rendering threads included in the rendering thread set is consistent with the target number of rendering threads.
[0471] Optionally, the printing module 704 is further configured to:
[0472] detecting the printing status information of the printing thread in real time, and terminating the operation of utilizing the printing thread and invoking the printing device to print the files to be printed of the plurality of printing tasks if printing failure is determined based on the printing status information;
[0473] The operation of utilizing the print thread to call a printing device to print the to-be-printed files of the multiple print tasks is re-executed.
[0474] Optionally, the rendering module 702 is further configured to:
[0475] receiving the plurality of printing tasks, and assigning a task priority to each of the printing tasks according to task information of each printing task, wherein the task priority is multiple;
[0476] From the rendering thread set, multiple rendering threads associated with the task priority are selected, and the to-be-printed information contained in multiple printing tasks is rendered in batches in parallel using the multiple rendering threads and the task priority to generate to-be-printed files corresponding to the multiple printing tasks.
[0477] Optionally, there are multiple printing devices, and the printing threads correspond one-to-one to the printing devices.
[0478] The printing module 704 is further configured to:
[0479] The task priorities and the print threads corresponding to the printing devices are used to call the printing devices in batches to print the to-be-printed files of the multiple printing tasks.
[0480] One or more embodiments of this specification provide a task processing device capable of separating file rendering operations from file printing operations. During the printing process, multiple rendering threads can be selected from a rendering thread set and used to render the to-be-printed information contained in multiple print tasks in parallel in batches, generating to-be-printed files corresponding to the multiple print tasks. The printing threads can then be used to call a printing device to print the to-be-printed files for the multiple print tasks. By processing the file rendering and printing operations in parallel through the rendering and printing threads, the efficiency of print task processing is improved, avoiding the problem of low print task processing efficiency when there are a large number of print tasks.
[0481] The above is a schematic scheme of a task processing device of this embodiment. It should be noted that the technical scheme of the task processing device and the technical scheme of the task processing method described above are of the same concept. For details not described in detail in the technical scheme of the task processing device, please refer to the description of the technical scheme of the task processing method described above.
[0482] Figure 8 8 shows a block diagram of a computing device 800 according to one embodiment of the present disclosure. Components of the computing device 800 include, but are not limited to, a memory 810 and a processor 820. The processor 820 is connected to the memory 810 via a bus 830, and a database 850 is used to store data.
[0483] The computing device 800 also includes an access device 840 that enables the computing device 800 to communicate via one or more networks 860. Examples of such networks include a public switched telephone network (PSTN), a local area network (LAN), a wide area network (WAN), a personal area network (PAN), or a combination of communication networks such as the Internet. The access device 840 may include one or more of any type of network interface (e.g., a network interface card (NIC)) whether wired or wireless, such as an IEEE 802.11 wireless local area network (WLAN) wireless interface, a Worldwide Interoperability for Microwave Access (Wi-MAX) interface, an Ethernet interface, a universal serial bus (USB) interface, a cellular network interface, a Bluetooth interface, or a near field communication (NFC) interface.
[0484] In one embodiment of the present specification, the above components of the computing device 800 and Figure 8 Other components not shown in the figure may also be connected to each other, for example, via a bus. Figure 8 The computing device structure block diagram shown is for illustrative purposes only and is not intended to limit the scope of this specification. Those skilled in the art may add or replace other components as needed.
[0485] Computing device 800 may be any type of stationary or mobile computing device, including a mobile computer or mobile computing device (e.g., a tablet computer, personal digital assistant, laptop computer, notebook computer, netbook computer, etc.), a mobile phone (e.g., a smartphone), a wearable computing device (e.g., a smartwatch, smart glasses, etc.), or other types of mobile devices, or a stationary computing device such as a desktop computer or personal computer (PC). Computing device 800 may also be a mobile or stationary server.
[0486] The processor 820 is configured to execute the following computer-executable instructions, which implement the steps of the above-mentioned task processing method when executed by the processor.
[0487] The various embodiments in this specification are described in a progressive manner. Similar portions between the various embodiments can be referenced to each other. Each embodiment focuses on the differences between the other embodiments. In particular, the computing device embodiment is generally similar to the task processing method embodiment, so its description is relatively simple. For relevant portions, refer to the description of the task processing method embodiment.
[0488] An embodiment of the present specification further provides a computer-readable storage medium storing a computer program / instruction. When the computer program / instruction is executed by a processor, the steps of the above-mentioned task processing method are implemented.
[0489] The various embodiments in this specification are described in a progressive manner. Similar portions between the various embodiments can be referenced to each other. Each embodiment focuses on the differences between the other embodiments. In particular, the computer-readable storage medium embodiment is generally similar to the task processing method embodiment, so its description is relatively simple. For relevant portions, refer to the description of the task processing method embodiment.
[0490] An embodiment of the present specification further provides a computer program product, including a computer program / instruction, which implements the steps of the above-mentioned task processing method when executed by a processor.
[0491] The above is a schematic solution of a computer program product of this embodiment. It should be noted that the technical solution of this computer program product and the technical solution of the task processing method described above are based on the same concept. For details not described in detail in the technical solution of the computer program product, please refer to the description of the technical solution of the task processing method described above.
[0492] The foregoing description of this specification describes specific embodiments. Other embodiments are within the scope of the appended claims. In some cases, the actions or steps recited in the claims can be performed in an order different from that described in the embodiments and still achieve the desired results. Furthermore, the processes depicted in the accompanying drawings do not necessarily require the specific order shown or the sequential order to achieve the desired results. In certain embodiments, multitasking and parallel processing are also possible or may be advantageous.
[0493] The computer instructions include computer program code, which may be in source code form, object code form, executable file, or some intermediate form. The computer-readable medium may include: any entity or device capable of carrying the computer program code, recording medium, USB flash drive, mobile hard disk, magnetic disk, optical disk, computer memory, read-only memory (ROM), random access memory (RAM), electric carrier signal, telecommunication signal, and software distribution medium. It should be noted that the content contained in the computer-readable medium may be appropriately increased or decreased according to the requirements of patent practice. For example, in some regions, according to patent practice, computer-readable media does not include electric carrier signals and telecommunication signals.
[0494] It should be noted that for the aforementioned method embodiments, for the sake of simplicity of description, they are all expressed as a series of action combinations, but those skilled in the art should be aware that the embodiments of this specification are not limited by the order of the actions described, because according to the embodiments of this specification, certain steps can be performed in other orders or simultaneously. Secondly, those skilled in the art should also be aware that the embodiments described in this specification are all preferred embodiments, and the actions and modules involved are not necessarily required by the embodiments of this specification.
[0495] In the above embodiments, the description of each embodiment has its own focus. For parts that are not described in detail in a certain embodiment, reference can be made to the relevant descriptions of other embodiments.
[0496] The preferred embodiments disclosed above are intended only to help illustrate this specification. The optional embodiments do not exhaustively describe all details, nor do they limit the invention to the specific embodiments described. Obviously, many modifications and variations can be made based on the content of the embodiments of this specification. This specification selects and specifically describes these embodiments in order to better explain the principles and practical applications of the embodiments of this specification, so that those skilled in the art can better understand and utilize this specification. This specification is limited only by the claims and their full scope and equivalents.< / monitoredsemaphore> < / batchprinttask> < / initialtask> < / hashmap> < / t> < / drawtask>
Claims
1. A task processing method, characterized in that: include: Selecting multiple rendering threads from the rendering thread set, and using the multiple rendering threads to render the to-be-printed information contained in the multiple printing tasks in batches in parallel to generate to-be-printed files corresponding to the multiple printing tasks; The printing thread is used to call a printing device to print the files to be printed of the multiple printing tasks.
2. The task processing method according to claim 1, characterized in that: The method of utilizing the print thread to call a printing device to print the files to be printed of the plurality of print tasks includes: A print thread is utilized to determine a target print task from the print tasks according to the task identifier of the print task, and a printing device is called to perform print processing on the to-be-printed file of the target print task.
3. The task processing method according to claim 2, characterized in that: The task identifier is a task sequence number; The utilizing the print thread to determine the target print task from the print tasks according to the task identifier of the print task includes: Using the print thread, determining the serial number of the task to be printed, and if the serial number of the task to be printed is consistent with the task serial number of the print task, confirming the print task as the target print task, The serial number of the task to be printed is confirmed according to the historical printing tasks of the printing thread in the history of printing processing, and the serial number of the task to be printed is the task serial number corresponding to the printing task that the printing thread currently needs to execute printing processing.
4. The task processing method according to claim 3, characterized in that: After determining the serial number of the task to be printed by using the print thread, the method further includes: When the task sequence number to be printed is inconsistent with the task sequence number of the printing task, the task sequence number of the candidate printing task stored in the printing thread queue is obtained. When the task sequence number of the to-be-printed task is consistent with the task sequence number of the candidate printing task, the candidate printing task is determined as the target printing task, and the printing task is stored as a candidate printing task in the printing thread queue according to the task sequence number. The candidate printing tasks are stored in the printing thread queue in order according to the task sequence numbers.
5. The task processing method according to any one of claims 3 to 4, characterized in that: Before determining the target print task from the print tasks according to the task identifier of the print task by using the print thread, the method further includes: Receive the plurality of printing tasks, and determine a historical task sequence number corresponding to the printing thread, wherein the historical task sequence number is a task sequence number allocated to the historical printing task; Based on the historical task sequence numbers, corresponding task sequence numbers are assigned to the plurality of printing tasks.
6. The task processing method according to any one of claims 1 to 4, characterized in that: The method of using the multiple rendering threads to render the to-be-printed information contained in the multiple printing tasks in batches in parallel to generate the to-be-printed files corresponding to the multiple printing tasks includes: Selecting a rendering thread queue associated with each print task from the rendering thread queues of the plurality of rendering threads, and storing each print task in the associated rendering thread queue; The plurality of rendering threads are used to render the to-be-printed information contained in the printing tasks in the rendering thread queue in batches in parallel to generate to-be-printed files corresponding to the plurality of printing tasks.
7. The task processing method according to claim 1, characterized in that: Before selecting a plurality of rendering threads from the rendering thread set, the method further includes: Determining the number of physical computing units and load status information of the printing device, wherein the physical computing unit is a computing unit that runs a rendering thread; Determining an initial number of rendering threads based on the number of units and the load status information, and determining a target number of rendering threads based on a thread number determination rule and the initial number of rendering threads; A rendering thread set is created based on the target number of rendering threads, wherein the number of rendering threads included in the rendering thread set is consistent with the target number of rendering threads.
8. The task processing method according to claim 1, characterized in that: The method of utilizing the print thread to call the printing device to print the files to be printed of the multiple print tasks further includes: detecting the printing status information of the printing thread in real time, and terminating the operation of utilizing the printing thread and invoking the printing device to print the files to be printed of the plurality of printing tasks if printing failure is determined based on the printing status information; The operation of utilizing the print thread to call a printing device to print the to-be-printed files of the multiple print tasks is re-executed.
9. The task processing method according to claim 1, characterized in that: The method of selecting a plurality of rendering threads from a rendering thread set and using the plurality of rendering threads to render information to be printed contained in a plurality of printing tasks in batches in parallel to generate files to be printed corresponding to the plurality of printing tasks includes: receiving the plurality of printing tasks, and assigning a task priority to each of the printing tasks according to task information of each printing task, wherein the task priority is multiple; From the rendering thread set, multiple rendering threads associated with the task priority are selected, and the to-be-printed information contained in multiple printing tasks is rendered in batches in parallel using the multiple rendering threads and the task priority to generate to-be-printed files corresponding to the multiple printing tasks.
10. The task processing method according to claim 9, characterized in that: There are multiple printing devices, and the printing threads correspond to the printing devices one by one. The method of utilizing the print thread to call a printing device to print the files to be printed of the plurality of print tasks includes: The task priorities and the print threads corresponding to the printing devices are used to call the printing devices in batches to print the to-be-printed files of the multiple printing tasks.
11. A task processing device, characterized in that: include: a rendering module configured to select a plurality of rendering threads from a rendering thread set, and use the plurality of rendering threads to render information to be printed contained in a plurality of printing tasks in batches in parallel to generate files to be printed corresponding to the plurality of printing tasks; The printing module is configured to utilize the printing thread to call the printing device to perform printing processing on the to-be-printed files of the multiple printing tasks.
12. A computing device, characterized in that include: memory and processor; The memory is used to store computer programs / instructions, and the processor is used to execute the computer programs / instructions. When the computer program / instructions are executed by the processor, the steps of the method according to any one of claims 1 to 10 are implemented.
13. A computer-readable storage medium, characterized in that It stores a computer program / instruction, which implements the steps of the method according to any one of claims 1 to 10 when executed by a processor.
14. A computer program product, characterized in that The method comprises a computer program / instruction, which implements the steps of the method according to any one of claims 1 to 10 when executed by a processor.
Citation Information
Cited By
POD printing monitoring method and system based on load prediction
CN120909539A
POD printing monitoring method and system based on load prediction
CN120909539B